using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MTRC.ODMS.DAL;
using MTRC.ODMS.DAL.SOM.CodeSetup;
using MTRC.ODMS.Model.SOM;
using MTRC.ODMS.Model.SOM.Event;
using AjaxControlToolkit;
using System.Xml;
using MTRC.ODMS.DAL.IR;
using APJ.Util;
using System.Xml.Xsl;
using MTRC.ODMS.DAL.COM;
using System.IO;
using APJ.Util.DataAccessHelper;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using MTRC.ODMS.BLL.SOM;


namespace MTRC.ODMS.Web.SOM.AdmissionRegistry
{
    /// <summary>
    /// Author:HeZhixiang
    /// </summary>
    public partial class AdmissionRegistryEntry : BasePage_SOM
    {

        #region Property

        //add by gordon 20150811 U147
        private int CurrentTempID
        {
            set { hdnTempID.Value = value.ToString(); }
            get { return hdnTempID.Value == "-1" ? -1 : Convert.ToInt32(hdnTempID.Value); }
        }

        /// <summary>
        /// MenuID
        /// </summary>
        protected override string MenuID
        {
            get
            {
                return "M140102";
            }
        }

        /// <summary>
        /// function item readonly
        /// </summary>
        private bool ReadOnly
        {
            get
            {
                bool _readOnly = false;
                bool.TryParse(string.Concat(ViewState["ReadOnly"]), out _readOnly);
                return _readOnly;
            }
            set
            {
                ViewState["ReadOnly"] = value;
            }
        }

        /// <summary>
        /// save model is 1:new;2:updata
        /// </summary>
        private int SaveModel
        {
            get
            {
                int _saveModel = 0;
                int.TryParse(string.Concat(ViewState["SaveModel"]), out _saveModel);
                return _saveModel;
            }
            set
            {
                ViewState["SaveModel"] = value;
            }
        }
        //add by benson 2015-09-07 begin
        /// <summary>
        /// Indicating whether working time is modified ,0:no modified; 1: is modified
        /// </summary>
        private int IsChangeWrkHour
        {
            get
            {
                int _isChangeWrkHour = 0;
                int.TryParse(string.Concat(ViewState["isChangeWrkHour"]), out _isChangeWrkHour);
                return _isChangeWrkHour;
            }
            set
            {
                ViewState["isChangeWrkHour"] = value;
            }
        }
        //add by benson 2015-09-07 end

        /// <summary>
        /// StationEventID  ISU45
        /// add by gordon 20160205
        /// </summary>
        protected int StationEventID
        {
            get
            {
                //update by gordon 20160218 ISU45
                //if (ViewState[MTRC.ODMS.BLL.COM.Session.SOM_StationEventID] == null)
                //{
                //    return -1;
                //}
                //else
                //{
                //    return int.Parse(ViewState[MTRC.ODMS.BLL.COM.Session.SOM_StationEventID].ToString());
                //}
                int stationEventID = -1;
                int.TryParse(Request.QueryString["StationEventID"], out stationEventID);
                return stationEventID > 0 ? stationEventID : -1;
                //update end by gordon 20160218 ISU45
            }
            //Comment by gordon 20160218 ISU45
            //set
            //{
            //    ViewState[MTRC.ODMS.BLL.COM.Session.SOM_StationEventID] = value;
            //}
        }

        #endregion

        #region Page Init And Load

        //comment by gordon 20160218 ISU45
        //private void SetCurrentStationEventID()
        //{
        //    int stationEventID = -1;
        //    int.TryParse(string.Concat(Request.QueryString["StationEventID"]).Trim(), out stationEventID);
        //    //if (stationEventID > 0)
        //    //{
        //    //    this.StationEventID = stationEventID;
        //    //}
        //    //this.StationEventID = stationEventID;
        //}

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(ChangeLanguage_Function);
            this.grdFireSystem.RowDeleting += new GridViewDeleteEventHandler(grdFireSystem_RowDeleting);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //Modify by elvis on 20180131 for SER-2018056 （default not load  SignaturePaint.）-->
            if (CommonData.GetCharVal("SOM_Sign_Must").Trim() == "Y")
            {
                emSignMust.Visible = true;
            }
            //<--Modify by elvis on 20180131 for SER-2018056 （default not load  SignaturePaint.）

            //add by gordon 20150811 U147
            if (CheckUnRestore())
                return;


            this.TracePageChange = true;
            //this.SetCurrentStationEventID();//comment by gordon 20160218 ISU45

            if (!IsPostBack)
            {
              
                //add by tim 20160407 for save signature into database
                using (SqlDataReader drStationEventSignReaderArrive = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARStationEventSign(this.StationEventID, 1))
                {
                    if (!drStationEventSignReaderArrive.HasRows)
                    {
                        ucSignatureNew1.clearSignSession();
                    }
                }
                //end add
                Session["AR_FireInitDateTime"] = null;//Add by jack 20151223 U291 The amendment history on isolation time is incorrect.
                // add by dylan 20151030 for u275.1 
                this.grdFireSystem.PageSize = this.GridViewPageDefaultSize();
                this.grdAssetLoan.PageSize = this.GridViewPageDefaultSize();

                //add by jack 20150810 for U70
                if (!string.IsNullOrEmpty(Request.QueryString["StationEventID"]))
                {
                    int stationEventID;
                    int.TryParse(Request.QueryString["StationEventID"], out stationEventID);
                    string messageKey = "SOM_NotPermissionStation";
                    if (base.NoPremissionToAccess(this.MenuID, stationEventID, "M140102_F6", "", ref messageKey))
                    {
                        //update by gordon 20150902 U70
                        //this.PAlert(this.GetMessage("SOM_NotPermissionStation"), 1, "window.location=AdmissionRegistryEnquiry.aspx");
                        Response.Write("<script>alert('" + this.GetMessage(messageKey) + "');window.location.href='AdmissionRegistryEnquiry.aspx'</script>");
                        Response.End();
                        //this.Response.Redirect(APJ.Util.Utility.GetHttpHost(this.Request) + "/SOM/AdmissionRegistry/AdmissionRegistryEnquiry.aspx");
                    }
                }
                //add by gordon 20150902 U70
                else
                {
                    if (!IsValidStation(this.ODMUser.LocationID))
                    {
                        Response.Write("<script>alert('" + this.GetMessage("SOM_NotValidStation") + "');window.location.href='AdmissionRegistryEnquiry.aspx?IsReject=1'</script>");
                        Response.End();
                    }
                }

                //this.PAlert(this.GetMessage("SOM_LegalStationCheck"));
                //this.Response.Redirect(APJ.Util.Utility.GetHttpHost(this.Request) + "/SOM/AdmissionRegistry/AdmissionRegistryEnquiry.aspx");

                /****************************/

                //add by jack 20150702 for U50.2
                if (CommonData.GetCharVal("SOM_CQAQual_Realtime_Enable").Trim() == "Y")
                {
                    oldCompany.Style.Add("display", "none");
                    newCompany.Style.Add("display", "block");
                    oldQualification.Style.Add("display", "none");
                    newQualification.Style.Add("display", "block");
                }
                else
                {
                    oldCompany.Style.Add("display", "block");
                    newCompany.Style.Add("display", "none");
                    oldQualification.Style.Add("display", "block");
                    newQualification.Style.Add("display", "none");
                }

                SetLanguage();
                CustomInitializtion();
                string company = ddlDepartmentCompany.Text;
                ScriptManager.RegisterStartupScript(Page, typeof(string), "", "InitCombobox();", true); //add by jack for U50.2
            }
            else
            {
                this.IsServerChanged = true;
                this.AjaxUpdateIsServerChanged();
            }

            if (this.SaveModel == 2)
            {
                oldCompany.Style.Add("display", "block");
                newCompany.Style.Add("display", "none");
                //oldQualification.Style.Add("display", "none");
                //newQualification.Style.Add("display", "block");
                if (CommonData.GetCharVal("SOM_CQAQual_Realtime_Enable").Trim() == "Y")
                {
                    newQualification.Style.Add("display", "block");
                    oldQualification.Style.Add("display", "none");
                }
                else
                {
                    oldQualification.Style.Add("display", "block");
                    newQualification.Style.Add("display", "none");
                }
                this.txtQualification.Enabled = false;
                this.btnMoreQualification.Enabled = false;

                this.txtStaffName.Enabled = false;
                this.txtDepartmentCompany.Enabled = false;
                //update by gordon 20150826 U168.9
                //Qualification Enabled Logic not needed for now
                //if (this.hdnStatus.Value == "1")
                //{
                //    //update by gordon 20150818
                //    //this.ddlQualification.Enabled = false;
                //    this.ddlQualification.Enabled = true;
                //}
                this.ddlQualification.Enabled = false;
                //----------------------------
            }

            if (this.hdnPersonHoldQualKye.Value.Trim() != string.Empty)
            {
                SettingPageByStationEventPersonQual(BLL.SOM.TempData.GetCacheData(Convert.ToInt32(this.hdnPersonHoldQualKye.Value)).Tables[0], true);
            }
            this.btnMoreQualification.OnClientClick = "PersonSelectdQual('" + HttpUtility.UrlEncode(this.txtStaffID.Text.Trim()) + "');";
            ScriptManager.RegisterStartupScript(Page, typeof(string), "", "InitCombobox();", true);
            btnCopyAsNew.Enabled = false; //add by gordon 20160201 - Suspended
        }

        #endregion

        #region Method
        void ChangeLanguage_Function(object sender, EventArgs e)
        {
            SetLanguage();
            CustomInitializtion();
            this.txtStaffID_TextChanged(null, EventArgs.Empty);
        }

        /// <summary>
        /// set page element text multi-language
        /// </summary>
        private void SetLanguage()
        {
            this.btnOpenChangeEventTime.Attributes["title"] = this.GetLabel("SOM_AmendEventTime"); //"Change Asset Loan Event Time"; --Add by HY 2009-03-18

            //Floatig Menu
            btnNew.Text = this.GetLabel("COM_Add", false);
            btnSave.Text = this.GetLabel("COM_Save", false);
            //btnSaveBottom.Text = this.GetLabel("COM_Save", false);
            btnSaveTop.Text = this.GetLabel("COM_Save", false);
            btnCopyAsNew.Text = this.GetLabel("SOM_CopyAsNew", false);
            //btnPrint.Text = this.GetLabel("COM_Print", false);
            btnGotoJobDescription.Value = this.GetLabel("SOM_GoToWorkRequirement", false);
            btnGotoAssetLoan.Value = this.GetLabel("SOM_GoToAssetLoan", false);
            btnGotoFireLink.Value = this.GetLabel("SOM_GoToFireLink", false);
            // Update by dylan 20150623 for U48
            btnHandoverCheck.Text = this.GetLabel("SOM_HandoverCheck01", false);

            //Generalinformation part
            lblGeneralInformation.Text = this.GetLabel("SOM_GeneralInformation", false);

            lblRegistryNumberFlag.Text = this.GetLabel("SOM_RegNo", true);
            lblTransferredFlag.Text = this.GetLabel("SOM_Transferred", false);
            lblNewlyCreatedFlag.Text = this.GetLabel("SOM_NewlyCreated", false);
            //update by benson 2015.07.29  U102 begin
            //lblStatusFlag.Text = this.GetLabel("COM_Status", true);
            //lblHighLightFlag.Text = this.GetLabel("COM_HighLight", true);
            //update by benson 2015.07.29  U102 end
            lblArrivalTimeFlag.Text = this.GetLabel("SOM_StationArrivalTime", true);
            //update by benson 2015.07.29  U102 begin
            //lblChangeArrivalReasonFlag.Text = this.GetLabel("SOM_ReasonChangingArrivalTime", true);
            //update by benson 2015.07.29  U102 end
            lblStaffIDFlag.Text = this.GetLabel("SOM_ARStaffID", true);
            imgSearchStaff.ToolTip = this.GetLabel("SOM_ImgSearchStaff", false);
            btnTransferResponsibility.Text = this.GetLabel("SOM_TransferResponsibility", false);
            lblStaffNameFlag.Text = this.GetLabel("SOM_NameOfStaff", true);

            lblDepartmentCompanyFlag.Text = this.GetLabel("SOM_DepartmentCompany", true);
            lblContactNumberFlag.Text = this.GetLabel("COM_ContactNo", true);

            lblOrgUnitFlag.Text = this.GetLabel("SOM_OrgUnit", true);
            lblPersonNumberFlag.Text = this.GetLabel("SOM_NumberOfWorkers", true);

            lblQualificationFlag.Text = this.GetLabel("SOM_Qualification", true);
            //update by benson 2015.07.27 u102  begin
            ucSignatureNew1.SetLanguage();
            //ucSignatureArrivalBottom.SetLanguage();
            //lblDepartureTimeFlagBottom.Text = this.GetLabel("SOM_StationDepartureTime", true);
            //imgDepartureAmendBottom.ToolTip = this.GetLabel("SOM_DepartureTimeAmendReason", false);
            //imgCompletionTasksDeparture.ToolTip = this.GetLabel("SOM_CompletionTasksDeparture", false);
            //imgCompletionTasksDepartureBottom.ToolTip = this.GetLabel("SOM_CompletionTasksDeparture", false);
            //imgDepartureBottom.ToolTip = this.GetLabel("SOM_StationDeparture", false);
            //ucSignatureDeparture.SetLanguage();
            //ucSignatureDepartureBottom.SetLanguage();
            //update by benson 2015.07.27 u102  end
            lblRemarkFlag.Text = this.GetLabel("SOM_Remark", true);

            lblDepartureCaption.Text = this.GetLabel("SOM_StationDeparture", false);
            lblArrivalCaption.Text = this.GetLabel("SOM_StationArrivalCaption", true);
            //delete by gordon 20150820
            //lblDepartureTimeFlag.Text = this.GetLabel("SOM_StationDepartureTime", true);
            //update by benson 2015.07.29 u102  begin
            //imgDepartureAmend.ToolTip = this.GetLabel("SOM_DepartureTimeAmendReason", false);
            string departureImg = this.GetLabel("SOM_StationDepartureImg", false);
            if (!string.IsNullOrEmpty(departureImg))
            {
                imgDeparture.ToolTip = departureImg;
            }
            btnDeparture.ToolTip = this.GetLabel("SOM_StationDeparture", false);
            btnDeparture.Text = this.GetLabel("SOM_StationDepartureText", false);
            //update by benson 2015.07.29 u102  end
            //Work Requirement part
            lblWorkRequirementCaption.Text = this.GetLabel("SOM_WorkRequirement", false);

            lblFlagWorkCategory.Text = this.GetLabel("SOM_WorkCategory", true);
            lblFlagWorkSubCategory.Text = this.GetLabel("SOM_WorkSubCategory", true);
            imgSignatureRequired.ToolTip = this.GetLabel("SOM_DepartureSignatureIsRequired", false);

            lblTNNumber.Text = this.GetLabel("SOM_TNNumber", true);
            lblTransactionNumber.Text = this.GetLabel("SOM_TransactionNumber", true);
            lblPossessionCertNo.Text = this.GetLabel("SOM_PossessionCertNo", true);

            lblJobNature.Text = this.GetLabel("SOM_JobNature", true);
            lblJobLocation.Text = this.GetLabel("SOM_JobLocation", true);
            lblJobProtection.Text = this.GetLabel("SOM_JobProtection", true);

            lblEstimatedCompletionTime.Text = this.GetLabel("SOM_EstimateCompletionDateTime", true);
            lblHour.Text = this.GetLabel("SOM_Hours", true);

            //update by gorodn 20150803 U128.1
            //lblSupplement.Text = this.GetLabel("SOM_Remark", true);
            lblSupplement.Text = this.GetLabel("SOM_AdmRegWorkRequiredRemark", true);

            lblHandoverCheck.Text = this.GetLabel("SOM_HandoverCheck", true);

            lblEngineControlSystemFirst.Text = this.GetLabel("SOM_ECSControlPanelFirst", false);
            lblEngineControlSystemSecond.Text = this.GetLabel("SOM_ECSControlPanelSecond", false);
            lblEngineControlSystemThird.Text = this.GetLabel("SOM_ECSControlPanelThird", false);

            lblAssetLoanCaption.Text = this.GetLabel("SOM_AssetLoanSectionName", false);
            lblFireLinkCaption.Text = this.GetLabel("SOM_FireLink", false);

            //set hidden value for imgStaffType's tooltip
            DataTable dtEventPersonType = MTRC.ODMS.DAL.SOM.CodeSetup.CDEventPersonType.GetAll(this.LangCode, true);
            if (dtEventPersonType.Rows.Count > 0)
            {
                //string imgStaffTypeTooltip = dtEventPersonType.Rows[0]["EventPersonTypeCode"].ToString();
                this.hdnStaffTypeTooltip1.Value = dtEventPersonType.Rows[0]["EventPersonTypeCode"].ToString();
                this.hdnStaffTypeTooltip2.Value = dtEventPersonType.Rows[1]["EventPersonTypeCode"].ToString();
                this.hdnStaffTypeTooltip3.Value = dtEventPersonType.Rows[2]["EventPersonTypeCode"].ToString();
                this.hdnStaffTypeTooltip4.Value = dtEventPersonType.Rows[3]["EventPersonTypeCode"].ToString();
            }

            //AssetLoan
            lblALEventNumberFlag.Text = this.GetLabel("SOM_EventNo", true);
            lblALStatus.Text = this.GetLabel("COM_Status", false);
            lblSBCOrDBCCase.Text = this.GetLabel("SOM_SBCOrDBCCase", false);
            lblALHighLight.Text = this.GetLabel("COM_HighLight", true);
            //imgALEdit.ToolTip = this.GetLabel("COM_Edit", false);
            btnALEdit.Value = this.GetLabel("COM_Edit", false);

            btnAddNewAssetLoan.Text = this.GetLabel("SOM_AddNewAssetLoanItem");
            this.grdAssetLoan.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            //Fire system
            chkObsolete.Text = GetLabel("SOM_IncludeVoid", false);
            this.grdFireSystem.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            btnFireAdd.Text = this.GetLabel("SOM_AddNewAssetLoanItem");

            //bottom
            //update by benson 2015.07.27  U102 begin
            //lblArriveBottom.Text = this.GetLabel("SOM_StationArrivalCaption");
            //lblDepartureBottom.Text = this.GetLabel("SOM_StationDeparture");
            //update by benson 2015.07.27  U102 end


            //add by Edward 20150826 U179
            //ImageAddTransNo.ToolTip = this.GetLabel("SOM_TranNoAdd");
            //ImageClearTransNo.ToolTip = this.GetLabel("SOM_TranNoClear");

            //add by benson 2015.07.14 begin
            lblRemidner.Text = this.GetLabel("SOM_Remidner");
            btnCopyAllPossession.Text = this.GetLabel("SOM_CopyAllPossession");
            btnCopyProtectionOnly.Text = this.GetLabel("SOM_CopyProtectionOnly");
            btnBack.Text = this.GetLabel("SOM_Back");
            //add by benson 2015.07.14 end

            //add by gordon 20150724 U132.2
            txtTransactionNumber.ToolTip = this.GetLabel("SOM_TransactionNumberTips");
            txtTNNumber.ToolTip = this.GetLabel("SOM_TNNumberTips");


        }

        /// <summary>
        /// Custom element initial state of page
        /// </summary>
        private void CustomInitializtion()
        {
            ViewState["FlagReqSign"] = "0";
            ViewState["SubFlagReqSign"] = "0";

            ViewState["FlagProtect"] = "0";
            ViewState["SubFlagProtect"] = "0";

            lblNewlyCreatedFlag.Visible = false;

            InitDataControlBind();
            CheckQueryStringParameter();
            FunctionItemCheck();
        }

        /// <summary>
        /// Check FunctionItem
        /// </summary>
        /// <returns>value=1:can do all,  value=0:read only</returns>
        private void FunctionItemCheck()
        {
            if (DAL.Security.User.CanFunctionItemAccess("M140102_F1", this.ODMUser.UserProfileID, this.MenuID) == true || this.ReadOnly == true)
            {
                this.ReadOnly = true;
                //add by gordon 20150911 U204
                if (this.SaveModel == 1)
                {
                    Response.Write("<script>alert('" + this.GetMessage("SOM_NotAllowCreateNewEntry") + "');window.location.href='AdmissionRegistryEnquiry.aspx'</script>");
                    Response.End();
                    return;
                }
            }
            else
            {
                this.ReadOnly = false;
            }

            //BO-1436
            //update by gordon 20151021 U247
            //if (this.CurrentStation != this.CurrentEntryLocationID && this.StationEventID > 0)
            if (this.CurrentLocation != this.CurrentEntryLocationID && this.StationEventID > 0)
            {
                this.ReadOnly = true;
            }
            //-----------------------------

            ControlSettingByFunctionItem();
        }

        /// <summary>
        /// check Amend Time button whether can enable or not
        /// </summary>
        private void AmendTimeParameterCheck()
        {
            if (CommonData.GetCharVal("SOM_AR_CanAmendArrivalTime").ToString().Trim().ToUpper() == "Y")
            {
                btnOpenChangeEventTime.Visible = true;
            }
            else
            {
                btnOpenChangeEventTime.Visible = false;
            }
            //if (CommonData.GetCharVal("SOM_AR_CanAmendDepartTime").ToString().Trim().ToUpper() == "Y" && this.SaveModel != 1)
            //{
            //    //update by benson 2015.07.27  U102 begin
            //    //imgDepartureAmend.Enabled = true;
            //    if (hdnStatus.Value == "2")
            //    {
            //        btnDepartureAmend.Enabled = true;
            //        btnDepartureAmend.Visible = true;
            //    }
            //    //imgDepartureAmendBottom.Enabled = true;
            //    //update by benson 2015.07.27  U102 end
            //}
            //else
            //{
            //    //imgDepartureAmend.Enabled = false;
            //    btnDepartureAmend.Enabled = false;
            //    btnDepartureAmend.Visible = false;
            //    //update by benson 2015.07.27  U102 begin
            //    //imgDepartureAmendBottom.Enabled = false;
            //    //update by benson 2015.07.27  U102 end
            //}
        }

        /// <summary>
        /// check popup page whether readonly or not
        /// </summary>
        private void AmendTimeFunctionItem()
        {
            if (DAL.Security.User.CanFunctionItemAccess("M140102_F4", this.ODMUser.UserProfileID, this.MenuID) && this.ReadOnly == false)
            {
                this.btnOpenChangeEventTime.Attributes.Add("onclick", "EventAmendTime('False');");
                //this.btnAmendTime.Attributes.Add("onclick", "javascript:window.showModalDialog('True',window,'dialogHeight:220px;dialogWidth:500px;center:yes;resizable:no,scroll:no;status:no;unadorne:yes;scroll:no;'); return false;");
            }
            else
            {
                this.btnOpenChangeEventTime.Attributes.Add("onclick", "EventAmendTime('True');");
            }
        }

        /// <summary>
        /// setting control by FunctionItem
        /// </summary>
        private void ControlSettingByFunctionItem()
        {
            if (this.ReadOnly == true)
            {
                //general part
                //update by benson 2015.07.29  U102 begin
                //txtChangeArrivalReason.Enabled = false;
                //update by benson 2015.07.29  U102 end
                txtStaffID.Enabled = false;
                imgSearchStaff.Visible = false;
                //btnTransferResponsibility.Enabled = false; //Remove by jack 20151203 U288 enabled the Transfer button when eventstatus=2(completed)
                txtStaffName.Enabled = false;
                txtDepartmentCompany.Enabled = false;
                txtContactNo.Enabled = false;
                txtOrganizationUnit.Enabled = false;
                txtPersonNumber.Enabled = false;
                txtQualification.Enabled = false;
                btnMoreQualification.Enabled = false;
                //update by benson 2015.07.27 u102 begin
                this.ucSignatureNew1.SetEnable(false, 1);
                //ucSignatureArrivalBottom.SetEnable(false, 1);
                //imgCompletionTasksDeparture.Enabled = false; //need single set
                //imgCompletionTasksDepartureBottom.Enabled = false;
                //imgDepartureBottom.Enabled = false;
                //if (ucSignatureDeparture.GetSignatureFullFileName(2).ToString() != string.Empty)
                //{
                //    ucSignatureDeparture.SetEnable(false, 2, true);
                //    ucSignatureDepartureBottom.SetEnable(false, 2, true);
                //}
                //else
                //{
                //    ucSignatureDeparture.SetEnable(false, 2, false);
                //    ucSignatureDepartureBottom.SetEnable(false, 2, false);
                //}
                //update by benson 2015.07.27 u102 end
                txtRemark.Enabled = false;
                //imgDepartureAmend.Enabled = false;

                imgDeparture.Enabled = false;
                //add by benson 2015-07-23 begin
                btnDeparture.Enabled = false;
                btnCopyAllPossession.Enabled = false;
                btnCopyProtectionOnly.Enabled = false;
                imgWork.Enabled = false;
                //add by benson 2015-07-23 begin
                //work requirement
                ddlWorkCategory.Enabled = false;
                ddlSubCategory.Enabled = false;
                txtTNNumber.Enabled = false;
                //btnTNNumberMore.Enabled = false;
                txtTransactionNumber.Enabled = false;
                txtPossessionCertNo.Enabled = false;
                txtJobNature.Enabled = false;
                txtJobLocation.Enabled = false;
                txtJobProtection.Enabled = false;
                txtEstimatedCompletionTime.Enabled = false;
                txtSupplement.Enabled = false;
                chkHandoverCheck.Enabled = false;
                txtHandoverCheckDetail.Enabled = false;
                rblEngineControlSystemFirst0.Enabled = false;
                rblEngineControlSystemFirst1.Enabled = false;
                rblEngineControlSystemSecond0.Enabled = false;
                rblEngineControlSystemSecond1.Enabled = false;
                rblEngineControlSystemThird0.Enabled = false;
                rblEngineControlSystemThird1.Enabled = false;

                //flaot menu
                btnNew.Enabled = false;
                btnSave.Enabled = false;
                //btnSaveBottom.Enabled = false;
                btnSaveTop.Enabled = false;
                btnCopyAsNew.Enabled = false;
                //btnPrint.Enabled = false;

                //Fire System
                btnFireAdd.Enabled = false;
                grdFireSystem.Enabled = true;
                //Asset Loan
                btnAddNewAssetLoan.Enabled = false;
                grdAssetLoan.Enabled = true;

                // Update by dylan 20150623 for U48
                //btnHandoverCheck.Enabled = true;
                // edit by dylan 20150911 for u202
                btnHandoverCheck.Enabled = false;


                // add by dylan 20150902 for issue
                //ImageAddTransNo.Enabled = false;
                //ImageClearTransNo.Enabled = false;

                // add by dylan 20151015
                chkObsolete.Enabled = false;
                this.ucSignatureNew1.IsPhotoCaptureEnabled = false;
                this.ucSignatureNew1.IsHandWrittenEnabled = false;
            }
            //else
            //{
            //    AmendTimeParameterCheck();
            //}
            AmendTimeParameterCheck();
            AmendTimeFunctionItem();
            if (DAL.Security.User.CanFunctionItemAccess("M140102_F1", this.ODMUser.UserProfileID, this.MenuID) != true && hdnStatus.Value == "2")
            {
                btnNew.Enabled = true;
                btnCopyAsNew.Enabled = true;
                // add by dylan 20150911 for u202
                btnHandoverCheck.Enabled = true;

                //btnPrint.Enabled = true;

                //update by benson 2015.07.27  U102 begin
                //imgDepartureAmend.Enabled = true;
                //btnDepartureAmend.Enabled = true;
                //btnDepartureAmend.Visible = true;
                //imgDepartureAmendBottom.Enabled = true;
                //update by benson 2015.07.27  U102 end
            }
            SettingAssetLoanGridByData();
            SettingFireGridByDataBind();
            //comment by jack 20151021 for u239.2
            //ActivityListingClose();
            if (string.IsNullOrEmpty(Request.QueryString["IsSaveButton"]))
            {
                ActivityListingClose();
            }


            //add by gordon 20150827 U168.10
            imgDeparture.Visible = btnDeparture.Enabled;
            imgSignatureRequired.Visible = btnDeparture.Enabled;
        }

        /// <summary>
        /// close the record from ActivityListing page
        /// </summary>
        private void ActivityListingClose()
        {
            if (Request.QueryString["Destroy"] != null && Request.QueryString["Destroy"].ToString().ToLower() == "true" && this.ReadOnly == false && this.SaveModel == 2)
            {
                bool bIsTNProtected, bIsUserValidateNeeded;
                bIsTNProtected = IsTNProtected();
                bIsUserValidateNeeded = IsUserValidate();
                //this.ClientScript.RegisterStartupScript(typeof(BasePage), "DepartStation", string.Format("<script language='javascript'>DepartStation('{0}','{1}','{2}')</script>", this.MenuID, bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower()));
                this.ClientScript.RegisterStartupScript(typeof(BasePage), "ActivityListingClose", "<script language='javascript' type='text/javascript'>ActivityListingClose('" + this.MenuID + "','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "')</script>");
                //DepartureCheck(1);
            }
        }

        private void DepartureCheck(int DepartureType)
        {
            //"1"; save data and departure
            //"2": unsave data and popup depature;
            //"3"; to validated user and save data and departure
            int nRequirePasswordStaffInfoID = 0;
            string strRequirePasswordUserID = "";
            if (!ValidationBeforeSaveOperation(false))
            {
                return;
            }
            //update by benson 2015.07.28 U102 begin  Determine whether must sign
            if (ViewState["FlagReqSign"].ToString() == "1" || ViewState["SubFlagReqSign"].ToString() == "1")
            {
                hdnIsMustSig.Value = "1";
            }
            //update by benson end
            if (this.hdnFlagNeedValit.Value == "1")
            {
                int nStationEventID = Save(strRequirePasswordUserID, nRequirePasswordStaffInfoID);
                //add by gordon 20150827| Save before check U190
                SetLanguage();
                hdnFireSystemKey.Value = string.Empty;
                CustomInitializtion();
                //-----------------------
                this.IsServerChanged = false;
                //this.ClientScript.RegisterStartupScript(typeof(BasePage), "OpenDepartPage", "<script language='javascript'>OpenDepartPage('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>");
                //update by gordon 20150827 | Save before check U190
                //string strNeedValit1 = "<script language='javascript'>OpenDepartPage('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>";
                string strNeedValit1 = "<script language='javascript'>CheckUnRestore('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>";
                //----------------------------------------------
                //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "OpenDepartPage1", strNeedValit1, false);
                //updated by kernel for RegisterClienetScriptBlock error 20100625
                AjaxControlToolkit.ToolkitScriptManager.RegisterStartupScript(this, this.GetType(), "OpenDepartPage1", strNeedValit1, false);
            }
            if (this.hdnFlagNeedValit.Value == "2")
            {
                this.IsServerChanged = false;
                //this.ClientScript.RegisterStartupScript(typeof(BasePage), "OpenDepartPage", "<script language='javascript'>OpenDepartPage('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>");
                //update by gordon 20150827 | Save before check U190
                //string strNeedValit2 = "<script language='javascript'>OpenDepartPage('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>";
                string strNeedValit2 = "<script language='javascript'>CheckUnRestore('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>";
                //----------------------------------------------
                //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "OpenDepartPage2", strNeedValit2, false);
                //updated by kernel for RegisterClienetScriptBlock error 20100625
                AjaxControlToolkit.ToolkitScriptManager.RegisterStartupScript(this, this.GetType(), "OpenDepartPage2", strNeedValit2, false);
            }
            if (this.hdnFlagNeedValit.Value == "3")
            {
                if (UserValidate(out strRequirePasswordUserID, out nRequirePasswordStaffInfoID))
                {
                    int nStationEventID = Save(strRequirePasswordUserID, nRequirePasswordStaffInfoID);
                    //add by gordon 20150827| Save before check U190
                    SetLanguage();
                    hdnFireSystemKey.Value = string.Empty;
                    CustomInitializtion();
                    //-----------------------
                    this.IsServerChanged = false;
                    //this.ClientScript.RegisterStartupScript(typeof(BasePage), "OpenDepartPage", "<script language='javascript'>OpenDepartPage('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>");
                    //update by gordon 20150827 | Save before check U190
                    //string strNeedValit3 = "<script language='javascript'>OpenDepartPage('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>";
                    string strNeedValit3 = "<script language='javascript'>CheckUnRestore('" + this.StationEventID + "','" + this.MenuID + "','" + DepartureType + "')</script>";
                    //----------------------------------------------
                    //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "OpenDepartPage3", strNeedValit3, false);
                    //updated by kernel for RegisterClienetScriptBlock error 20100625
                    AjaxControlToolkit.ToolkitScriptManager.RegisterStartupScript(this, this.GetType(), "OpenDepartPage3", strNeedValit3, false);
                }
                else
                {
                    this.IsServerChanged = true;
                    this.AjaxUpdateIsServerChanged();
                }
            }
            hdnFlagNeedValit.Value = "";
            if (hdnFlagBookOff.Value != "")
            {
                if (hdnFlagBookOff.Value == "true")
                    if (Request.QueryString["isBack"] != null)
                    {
                        Response.Redirect("AdmissionRegistryEntry.aspx?StationEventID=" + this.StationEventID + "&isBack=1&pageID=" + Request.QueryString["pageID"].ToString());
                    }
                    else
                    {
                        Response.Redirect("AdmissionRegistryEntry.aspx?StationEventID=" + this.StationEventID);
                    }
                else
                    hdnFlagBookOff.Value = "";
            }
        }

        /// <summary>
        /// check QueryString Parameter is updata or new
        /// </summary>
        private void CheckQueryStringParameter()
        {
            ///add by benson 2015-06-29 begin
            if (Request.QueryString["isBack"] != null && Request.QueryString["isBack"].Trim() != string.Empty && Convert.ToInt32(Request.QueryString["isBack"].ToString()) > 0)
            {
                btnBack.Enabled = true;
            }
            else
            {
                btnBack.Enabled = false;
            }
            ///add by benson 2015-06-29 end
            if (Request.QueryString["StationEventID"] != null && Request.QueryString["StationEventID"].Trim() != string.Empty && Convert.ToInt32(Request.QueryString["StationEventID"].ToString()) > 0)
            {
                //add by gordon 20151028 U225
                Session[BLL.COM.Session.SOM_ResponsibilityTransfer + this.StationEventID.ToString()] = null;

                //this.StationEventID = int.Parse(Request.QueryString["StationEventID"].Trim());//comment by gordon 20160218 ISU45
                hdnStationEventID.Value = this.StationEventID.ToString();
                this.SaveModel = 2;
                //use StationEventID to view,updata,insert
                InitPageByStationEventID();
                //if (Request.QueryString["action"] != null && Request.QueryString["action"].Trim() != string.Empty && Request.QueryString["action"].ToString().Trim().ToLower() == "close")
                //{
                //    imgCompletionTasksDeparture_Click(null, null);
                //}
            }
            else
            {
                this.SaveModel = 1;
                //add new
                //this.StationEventID = -1;//comment by gordon 20160218 ISU45
                InitPageByNew();
            }
        }

        /// <summary>
        /// Bind data to control
        /// </summary>
        private void InitDataControlBind()
        {
            BindWorkCategory();
            BindWorkSubCategory();
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drCDECSStatusOneReader = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARCDECSStatusByIDReader(this.LangCode, 1))
            {
                drCDECSStatusOneReader.Read();
                SettingPageByCDECSStatusReader(drCDECSStatusOneReader, 1);
            }
            using (SqlDataReader drCDECSStatusOneReader2 = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARCDECSStatusByIDReader(this.LangCode, 2))
            {
                drCDECSStatusOneReader2.Read();
                SettingPageByCDECSStatusReader(drCDECSStatusOneReader2, 2);
            }

        }

        /// <summary>
        /// bind the value with WorkCategory control
        /// </summary>
        private void BindWorkCategory()
        {
            BindListControl(this.ddlWorkCategory, "AdmRegCategoryID", "Description", ODMS.DAL.SOM.CodeSetup.CDAdmRegCategory.GetAllWorkCategory(this.LangCode), true, "");
            ddlWorkCategory.SelectedIndex = 0;
            //U18 Update By Gordon 20150702
            //ddlWorkCategory.SelectedIndex = 0;
            ddlWorkCategory.SelectedIndex = 1;
            ddlWorkCategory_SelectedIndexChanged(null, null);
            //Update End
        }

        /// <summary>
        /// bind the value with WorkSubCategory control
        /// </summary>
        private void BindWorkSubCategory()
        {
            //Update By Gordon 20150702 U18
            //BindListControl(this.ddlSubCategory, "AdmRegSubCategoryID", "Description", ODMS.DAL.SOM.CodeSetup.CDAdmRegSubCategory.GetAllWorkSubCategoryForEntry(this.LangCode), true, "");

            if (ddlWorkCategory.SelectedIndex < 1)
            {
                BindListControl(this.ddlSubCategory, "AdmRegSubCategoryID", "Description", ODMS.DAL.SOM.CodeSetup.CDAdmRegSubCategory.GetAllWorkSubCategoryForEntry(this.LangCode), true, "");
            }
            else
            {
                if (ddlSubCategory.Items.Count > 1)
                {
                    ddlSubCategory.SelectedIndex = 1;
                }
            }
            //Update End
        }

        /// <summary>
        /// add by jack 20150701 for U50.2
        /// bind the value with DepartmentCompany control
        /// </summary>
        private void BindOUCompany(List<string> listOuCompany)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("OrganizationUnitDescValue");
            dt.Columns.Add("OrganizationUnitDescText");
            foreach (var item in listOuCompany)
            {
                dt.Rows.Add(item, item);
            }
            BindListControl(this.ddlDepartmentCompany, "OrganizationUnitDescValue", "OrganizationUnitDescText", dt, true, "");
            if (listOuCompany.Count == 1)
            {
                ddlDepartmentCompany.Items.RemoveAt(0);
                txtSelectedOU.Value = ddlDepartmentCompany.Items[0].Value;
            }
            else if (listOuCompany.Count == 0)
            {
                txtSelectedOU.Value = "";
                ddlDepartmentCompany.Items.Clear();
            }
            else
            {
                txtSelectedOU.Value = "";
                ddlDepartmentCompany.SelectedIndex = 0;
            }

            ScriptManager.RegisterStartupScript(Page, typeof(string), "", "InitCombobox();", true);
        }

        /// <summary>
        /// add by jack 20150701 for U50.3
        /// bind the value with Qualification control
        /// </summary>
        private void BindQualification(List<string> listQualification)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("QualificationValue");
            dt.Columns.Add("QualificationText");
            foreach (var item in listQualification)
            {
                if (!string.IsNullOrEmpty(item.Trim()) && item != this.GetMessage("SOM_QualificationNotFound"))
                {
                    dt.Rows.Add(item, item);
                }
            }
            BindListControl(this.ddlQualification, "QualificationValue", "QualificationText", dt, true, "");
            /*Comment by jack 20150916 for U212*/
            //if (dt.Rows.Count == 1)
            //{
            //    ddlQualification.Items.RemoveAt(0);
            //}
            if (dt.Rows.Count == 1)
            {
                ddlQualification.Items[1].Selected = true;
            }
            else if (dt.Rows.Count == 0)
            {
                ddlQualification.Items.Clear();
                ListItem item = new ListItem();
                item.Text = this.GetMessage("SOM_QualificationNotFound");
                item.Value = "";
                ddlQualification.Items.Add(item);
                ddlQualification.SelectedIndex = 0;
            }
            else
            {
                ddlQualification.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// Init Page By StationEventID when StationEventID exist
        /// </summary>
        private void InitPageByStationEventID()
        {
            btnMoreQualification.Enabled = true; //need single set
            //update by benson 2015.07.27 u102 begin
            this.ucSignatureNew1.InitUCSignatureValue(1, 1, "");
            this.ucSignatureNew1.SetEnable(true, 1);
            //ucSignatureArrivalBottom.InitUCSignatureValue(1, 1, "");
            //ucSignatureArrivalBottom.SetEnable(true, 1);
            //ucSignatureDeparture.InitUCSignatureValue(2, 1, "");
            //ucSignatureDeparture.SetEnable(false, 2, false);//need single set
            //ucSignatureDepartureBottom.InitUCSignatureValue(2, 1, "");
            //ucSignatureDepartureBottom.SetEnable(false, 2, false);//need single set
            //update by benson 2015.07.27 u102 end
            imgSearchStaff.Visible = false;
            txtStaffID.Enabled = false;
            txtStaffName.Enabled = false;
            txtDepartmentCompany.Enabled = false;
            txtContactNo.Enabled = false;
            txtOrganizationUnit.Enabled = false;
            ddlDepartmentCompany.Enabled = false;
            ddlQualification.Enabled = false;

            btnTransferResponsibility.Enabled = true; //need single set
            //update by benson 2015.07.27 u102 begin
            //imgCompletionTasksDeparture.Enabled = true; //need single set
            //imgCompletionTasksDepartureBottom.Enabled = true;
            //imgDepartureBottom.Enabled = true; //need single set
            //lblDepartureTimeBottom.Text = "";
            btnDeparture.Enabled = true;
            //update by benson 2015.07.27 u102 end
            imgDeparture.Enabled = true; //need single set

            //lblDepartureTime.Text = this.FormatDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime(), true);
            //lblDepartureTimeBottom.Text = this.FormatDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime(), true);
            lblDepartureTime.Text = "";

            hdnDepartDate.Value = "";
            hdnDepartTime.Value = "";
            //hdnDepartDate.Value = DateTime.Parse(lblDepartureTime.Text.ToString()).ToString("dd/MM/yyyy");
            //hdnDepartTime.Value = DateTime.Parse(lblDepartureTime.Text.ToString()).ToString("hh:mm");
            //string[] split = lblDepartureTime.Text.Split(new char[] { ' ' });
            //hdnDepartDate.Value = split[0];
            //hdnDepartTime.Value = split[1];


            GetDataForPage();
            NochangeAfterSavedParameterCheck();
        }

        /// <summary>
        /// Check parameter SOM_AR_NochangeAfterSaved whether true or not
        /// </summary>
        private void NochangeAfterSavedParameterCheck()
        {
            bool bResult = false;
            if (DAL.CommonData.GetCharVal("SOM_AR_NochangeAfterSaved").ToString().Trim().ToUpper() == "Y")
            {
                bResult = true;
            }
            ddlWorkCategory.Enabled = !bResult;
            ddlSubCategory.Enabled = !bResult;
            txtTNNumber.Enabled = !bResult;
            txtPossessionCertNo.Enabled = !bResult;
            txtJobNature.Enabled = !bResult;
            txtJobLocation.Enabled = !bResult;
            txtJobProtection.Enabled = !bResult;
            txtEstimatedCompletionTime.Enabled = !bResult;
        }

        /// <summary>
        /// Init Page By New when need add new 
        /// </summary>
        private void InitPageByNew()
        {
            lblArrivalTime.Text = this.FormatDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime(), true);

            //add by gordon 20160216 ISU51
           // BLL.SOM.Log.Logger("AR->InitPageByNew->lblArrivalTime:" + lblArrivalTime.Text,4,ODMUser.ID,ODMUser.UserGroupName);

            string[] split = lblArrivalTime.Text.Split(new char[] { ' ' });
            hdnArrivalDate.Value = split[0];
            hdnArrivalTime.Value = split[1];

            hdnArrivalTimePrototype.Value = this.FormatDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime(), true);
            lblTransferredFlag.Visible = false;
            lblNewlyCreatedFlag.Visible = true;
            btnOpenChangeEventTime.Attributes.Add("style", "background-color: inherit;");
            //imgStatus.ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_OS.gif";
            //imgStatus.ToolTip = this.GetLabel("SOM_OS", false);

            imgSearchStaff.Visible = true;
            txtStaffID.Enabled = true;
            txtStaffName.Enabled = true;
            txtDepartmentCompany.Enabled = true;
            txtContactNo.Enabled = true;
            txtOrganizationUnit.Enabled = false;
            txtPersonNumber.Text = CommonData.GetNumVal("SOM_AR_NumberOfWorkers").ToString();

            btnTransferResponsibility.Enabled = false;
            //lblMustInput.Visible = true;  --alter by hzx,on 20090206
            btnMoreQualification.Visible = true;
            //update by benson 2015.07.27  U102  begin
            this.ucSignatureNew1.InitUCSignatureValue(1, 2, "");
            ucSignatureNew1.SetEnable(true, 1);
            //ucSignatureArrivalBottom.InitUCSignatureValue(1, 1, "");
            //ucSignatureArrivalBottom.SetEnable(true, 1);
            //ucSignatureDeparture.InitUCSignatureValue(2, 1, "");
            //ucSignatureDeparture.SetEnable(false, 2, false);
            //ucSignatureDepartureBottom.InitUCSignatureValue(2, 1, "");
            //ucSignatureDepartureBottom.SetEnable(false, 2, false);
            //imgDepartureAmendBottom.Enabled = false;
            //imgCompletionTasksDeparture.Enabled = false;
            //imgCompletionTasksDepartureBottom.Enabled = false;
            //imgDepartureBottom.Enabled = false;
            btnDeparture.Enabled = false;
            //imgDepartureAmend.Enabled = false;
            btnDepartureAmend.Enabled = false;
            btnDepartureAmend.Visible = false;
            //update by benson 2015.07.27  U102  end


            imgDeparture.Enabled = false;

            chkHandoverCheck.Checked = false;
            txtHandoverCheckDetail.Enabled = false;

            btnFireAdd.Enabled = true;
            grdFireSystem.Enabled = true;
            btnAddNewAssetLoan.Enabled = true;
            grdAssetLoan.Enabled = true;

            //SettingAssetLoanGridByData();
            //SettingFireGridByDataBind();
        }

        private int CurrentEntryLocationID; //BO-1436

        /// <summary>
        /// Get General data
        /// </summary>
        private void GetDataForPage()
        {
            //add by gordon 20150812 | Cleare Tip & Show Departure Sign
            int statusID = -1;
            string departureSignFile = string.Empty;

            int nPersonID = -1;
            //edit by hjh 20120519 for DataReader not close
            //setting control associate StationEvent table
            using (SqlDataReader drAREntryGeneral = ODMS.BLL.SOM.Event.StationEventAdmReg.AREntryGeneralReader(this.StationEventID, this.LangCode))
            {
                if (drAREntryGeneral.HasRows)
                {
                    drAREntryGeneral.Read();

                    //add by gordon 20150812 | Get Event Status
                    statusID = Convert.ToInt32(drAREntryGeneral["EventStatusID"]);

                    nPersonID = Convert.ToInt32(drAREntryGeneral["StationEventPersonID"].ToString());
                    hdnStationEventPersonID.Value = drAREntryGeneral["StationEventPersonID"].ToString();
                    this.CurrentEntryLocationID = Convert.ToInt32(drAREntryGeneral["LocationID"].ToString()); //BO-1436
                    SettingPageByStationEvent(drAREntryGeneral);
                }
            }

            //setting control associate StationEventPerson table
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drARStationEventPerson = ODMS.BLL.SOM.Event.StationEventAdmReg.GetStationEventPersonByIDReader(this.StationEventID))
            {
                if (drARStationEventPerson.HasRows)
                {
                    drARStationEventPerson.Read();
                    SettingPageByStationEventPerson(drARStationEventPerson);
                }
            }


            //setting control associate Arrive time of StationEventAmendTime
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drStationEventAmendTimeArrive = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARStationEventAmendTimeReader(this.LangCode, 1, this.StationEventID))
            {
                if (drStationEventAmendTimeArrive.HasRows)
                {
                    drStationEventAmendTimeArrive.Read();
                    SettingPageByStationEventAmendTime(drStationEventAmendTimeArrive, 1);
                }
            }

            //setting control associate depart time of StationEventAmendTime
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drStationEventAmendTimeDepart = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARStationEventAmendTimeReader(this.LangCode, 2, this.StationEventID))
            {
                if (drStationEventAmendTimeDepart.HasRows)
                {
                    drStationEventAmendTimeDepart.Read();
                    SettingPageByStationEventAmendTime(drStationEventAmendTimeDepart, 2);
                }
            }

            //setting control associate StationEvent table
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drAREntryStaffInfo = ODMS.BLL.SOM.Event.StationEventAdmReg.AREntryStaffInformationReader(nPersonID, this.LangCode))
            {
                if (drAREntryStaffInfo.HasRows)
                {
                    drAREntryStaffInfo.Read();
                    SettingPageByStaffInfo(drAREntryStaffInfo);
                }
            }

            //setting control associate StationEventAdmReg table
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drAREntryStationEventAdmRegReader = ODMS.BLL.SOM.Event.StationEventAdmReg.AREntryStationEventAdmRegReader(this.StationEventID))
            {
                if (drAREntryStationEventAdmRegReader.HasRows)
                {
                    drAREntryStationEventAdmRegReader.Read();
                    SettingPageByStationEventAdmReg(drAREntryStationEventAdmRegReader);
                }
            }

            //setting control associate SOM_StationEventPersonQual table
            //update by jack 20150703 for U50.2
            DataTable dtPersonHoldQual = MTRC.ODMS.DAL.SOM.Event.StationEventAdmRegDa.PersonHoldQualGet(Convert.ToInt32(hdnStationEventPersonID.Value), Convert.ToInt32(hdnStaffType.Value)).Tables[0];
            SettingPageByStationEventPersonQual(dtPersonHoldQual, false);
            //if (CommonData.GetCharVal("SOM_CQAQual_Realtime_Enable") != "Y") {
            //    DataTable dtPersonHoldQual = MTRC.ODMS.DAL.SOM.Event.StationEventAdmRegDa.PersonHoldQualGet(Convert.ToInt32(hdnStationEventPersonID.Value), Convert.ToInt32(hdnStaffType.Value)).Tables[0];
            //    SettingPageByStationEventPersonQual(dtPersonHoldQual);
            //}
            //else {
            //}


            //getting Arrive Signature  
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drStationEventSignReaderArrive = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARStationEventSignReader(this.StationEventID, 1, nPersonID))
            {
                if (drStationEventSignReaderArrive.HasRows)
                {
                    drStationEventSignReaderArrive.Read();
                    SettingPageByStationEventSignReader(drStationEventSignReaderArrive, 1);
                }
            }

            //getting Departure Signature 
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drStationEventSignReaderDepart = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARStationEventSignReader(this.StationEventID, 2, nPersonID))
            {
                if (drStationEventSignReaderDepart.HasRows)
                {
                    drStationEventSignReaderDepart.Read();
                    departureSignFile = drStationEventSignReaderDepart["SignFileName"].ToString();
                    SettingPageByStationEventSignReader(drStationEventSignReaderDepart, 2);
                }
            }
            //SettingAssetLoanGridByData();
            //SettingFireGridByDataBind();

            //add by gordon 20150812 | Cleare Tip
            if (statusID == 2)
            {
                imgDeparture.ToolTip = "";
                if (!string.IsNullOrEmpty(departureSignFile))
                {
                    //add by gordon 20160114 - change save sign file from full to relative U297
                    string realPath = APJ.Util.Utility.GetAppSetting("SOM_SignatureFilePath");
                    if (realPath.LastIndexOf("\\") != realPath.Length - 1)
                        realPath += "\\";

                    departureSignFile = realPath + departureSignFile;
                    //end by gordon 20160114

                    departureSignFile = departureSignFile.Replace("\\", "\\\\");
                    departureSignFile = HttpUtility.HtmlEncode(departureSignFile);
                    imgSignature.ImageUrl = "~/Images/SOM/Sign_Signature.gif";
                    string script = "OpenHandWrittenFormDeparture('true','2','" + departureSignFile + "')";    //modify by tim 20160407 for save signature into database
                    imgSignature.Style.Add("cursor", "hand");
                    imgSignature.Attributes.Add("onclick", script);
                }

                //add by gordon 20150827 U168.10
                imgSignature.Visible = true;
                //imgSignature
            }
        }

        /// <summary>
        /// Setting Page By StationEvent table
        /// </summary>
        /// <param name="AREntryGeneral"></param>
        private void SettingPageByStationEvent(SqlDataReader AREntryGeneral)
        {
            if (AREntryGeneral["EventTypeID"].ToString() != "1")
            {
                Response.Redirect(APJ.Util.Utility.GetHttpHost(this.Request) + "/SOM/AdmissionRegistry/AdmissionRegistryEnquiry.aspx");
            }
            lblRegistryNumber.Text = AREntryGeneral["EventNo"].ToString();
            if (AREntryGeneral["EventStatusID"].ToString() == "1")
            {
                imgStatus.ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_OS.gif";
            }
            else if (AREntryGeneral["EventStatusID"].ToString() == "2")
            {
                imgStatus.ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_COM.gif";
                this.ReadOnly = true;
            }
            else
            {
                imgStatus.ImageUrl = Request.ApplicationPath.ToString() + "/Images/SOM/EventStatus_Void.gif";
                this.ReadOnly = true;
            }
            imgStatus.ToolTip = AREntryGeneral["EventStatusDesc"].ToString();
            hdnStatus.Value = AREntryGeneral["EventStatusID"].ToString();
            //update by benson 2015.08.27 u183.3 begin
            if (AREntryGeneral["EventStatusID"].ToString() == "2")
            {
                imgHighLight.ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                imgHighLight.ToolTip = this.GetLabel("SOM_HighLightNormal", false);
            }
            //update by benson 2015.08.27 u183.3 end
            else if (AREntryGeneral["HighLight"].ToString() == "0")
            {
                imgHighLight.ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                imgHighLight.ToolTip = this.GetLabel("SOM_HighLightNormal", false);
            }
            else if (AREntryGeneral["HighLight"].ToString() == "1")
            {
                imgHighLight.ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Yellow.gif";
                imgHighLight.ToolTip = this.GetLabel("SOM_HighLightYellow", false);
            }
            else if (AREntryGeneral["HighLight"].ToString() == "2")
            {
                imgHighLight.ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Red.gif";
                imgHighLight.ToolTip = this.GetLabel("SOM_HighLightRed", false);
            }
            else
            {
                imgHighLight.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
            }
            hdnHighLight.Value = AREntryGeneral["HighLight"].ToString();
            lblArrivalTime.Text = this.FormatDateTime(AREntryGeneral["EventTime"], true);

            //add by gordon 20160216 ISU51
            //BLL.SOM.Log.Logger("AR->SettingPageByStationEvent->lblArrivalTime:" + lblArrivalTime.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

            //add on 2008.12.12 by hzx "background-color: inherit;"
            if (AREntryGeneral["HasAmendArriveTimeCount"].ToString() != "0")
            {
                string strColor = CommonData.GetStrVal("SOM_AmendedEventTime_Color").ToString();
                btnOpenChangeEventTime.Attributes.Add("style", "BACKGROUND-COLOR:" + strColor);
            }

            //hdnArrivalDate.Value = DateTime.Parse(lblArrivalTime.Text.ToString()).ToString("dd/MM/yyyy");
            //hdnArrivalTime.Value = DateTime.Parse(lblArrivalTime.Text.ToString()).ToString("hh:mm");
            string[] split = lblArrivalTime.Text.Split(new char[] { ' ' });
            hdnArrivalDate.Value = split[0];
            hdnArrivalTime.Value = split[1];
            hdnArrivalTimePrototype.Value = this.FormatDateTime(AREntryGeneral["EventTime"], true);
            txtRemark.Text = AREntryGeneral["Remark"].ToString();

            if (MTRC.ODMS.DAL.COM.Util.DateTimeFromDB(AREntryGeneral["EventCompleteTime"]) != DateTime.MinValue)
            {
                lblDepartureTime.Text = this.FormatDateTime(MTRC.ODMS.DAL.COM.Util.DateTimeFromDB(AREntryGeneral["EventCompleteTime"]), true);
                //update by benson 2015.07.27  U102 begin
                //lblDepartureTimeBottom.Text = this.FormatDateTime(MTRC.ODMS.DAL.COM.Util.DateTimeFromDB(AREntryGeneral["EventCompleteTime"]), true);
                //update by benson 2015.07.27  U102 end
                string[] strSplit = lblDepartureTime.Text.Split(new char[] { ' ' });
                hdnDepartDate.Value = strSplit[0];
                hdnDepartTime.Value = strSplit[1];
            }

            //txtEstimatedCompletionTime.Text = AREntryGeneral["EstimatedWrkHour"].ToString().Remove(AREntryGeneral["EstimatedWrkHour"].ToString().Length - 1, 1);
            decimal oneFractionHr = MTRC.ODMS.DAL.COM.Util.DecimalFromDB(AREntryGeneral["EstimatedWrkHour"]);
            if (oneFractionHr != 0)
            {
                oneFractionHr = decimal.Round(oneFractionHr, 1);
                this.txtEstimatedCompletionTime.Text = oneFractionHr.ToString();
                DateTime tempDateTime = MTRC.ODMS.DAL.COM.Util.DateTimeFromDB(AREntryGeneral["EventTime"]);
                double tempHr = double.Parse(oneFractionHr.ToString());
                tempDateTime = tempDateTime.AddHours(tempHr);
                this.lblShouldCompletionTime.Text = this.FormatDateTime(tempDateTime, true);
            }
            //lblShouldCompletionTime.Text = this.FormatDateTime((Convert.ToDateTime(AREntryGeneral["EventCompleteTime"].ToString())), true);

            if (AREntryGeneral["FlagHandover"] != DBNull.Value)
            {
                if (AREntryGeneral["FlagHandover"].ToString().ToUpper() == "true".ToUpper())
                {
                    chkHandoverCheck.Checked = true;
                    txtHandoverCheckDetail.Enabled = true;
                }
                else
                {
                    chkHandoverCheck.Checked = false;
                    txtHandoverCheckDetail.Enabled = false;
                }
            }
            txtHandoverCheckDetail.Text = AREntryGeneral["HandoverNote"].ToString();
            hdnStationEventLastUpdataTime.Value = this.FormatDateTime(Convert.ToDateTime(AREntryGeneral["LastUpdTime"]), true, true);
        }

        /// <summary>
        /// Get StationEventPerson 
        /// </summary>
        /// <param name="StationEventPersonList"></param>
        private void SettingPageByStationEventPerson(SqlDataReader ARStationEventPerson)
        {
            if (ARStationEventPerson["SequenceNo"] != null && Convert.ToInt32(ARStationEventPerson["SequenceNo"].ToString()) > 1)
            {
                lblTransferredFlag.Visible = true;
            }
            else
            {
                lblTransferredFlag.Visible = false;
            }
        }

        /// <summary>
        /// Setting Page By Staff Information
        /// </summary>
        /// <param name="AREntryStaffInfo"></param>
        private void SettingPageByStaffInfo(SqlDataReader AREntryStaffInfo)
        {
            this.txtStaffID.Text = MTRC.ODMS.DAL.COM.Util.StringFromDB(AREntryStaffInfo["StaffID"]);

            if (hdnStatus.Value == "2" && Util.StringFromDB(AREntryStaffInfo["MaskedStaffID"]) != string.Empty)
            {
                this.txtStaffID.Text = Util.StringFromDB(AREntryStaffInfo["MaskedStaffID"]);
            }
            //add by jack 20150706 for U50.2
            this.txtStaffName.Text = MTRC.ODMS.DAL.COM.Util.StringFromDB(AREntryStaffInfo["StaffName"]);
            this.txtDepartmentCompany.Text = MTRC.ODMS.DAL.COM.Util.StringFromDB(AREntryStaffInfo["DepartmentCompany"]);
            this.txtContactNo.Text = MTRC.ODMS.DAL.COM.Util.StringFromDB(AREntryStaffInfo["Tel"]);

            hdnStaffType.Value = AREntryStaffInfo["EventPersonTypeID"].ToString();
            hdnStaffTypeProto.Value = AREntryStaffInfo["EventPersonTypeID"].ToString();
            hdnStaffOrExtPartyID.Value = AREntryStaffInfo["StaffOrExtPartyID"].ToString();
            hdnExtPartyStaffSnapShotID.Value = AREntryStaffInfo["ExtPartyStaffSnapShotID"].ToString(); //add 2009.01.04
            if (AREntryStaffInfo["EventPersonTypeID"].ToString() == "1")
            {
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/SOM/StaffType_Staff.gif";
                this.imgStaffType.ToolTip = hdnStaffTypeTooltip1.Value;
                //lblMustInput.Visible = true;  --alter by hzx,on 20090206
                btnMoreQualification.Visible = true;
            }
            else if (AREntryStaffInfo["EventPersonTypeID"].ToString() == "2")
            {
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/SOM/StaffType_CQAContractor.gif";
                this.imgStaffType.ToolTip = hdnStaffTypeTooltip2.Value;
                //lblMustInput.Visible = true;  --alter by hzx,on 20090206
                btnMoreQualification.Visible = true;
            }
            else if (AREntryStaffInfo["EventPersonTypeID"].ToString() == "3")
            {
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/SOM/StaffType_StationContractor.gif";
                this.imgStaffType.ToolTip = hdnStaffTypeTooltip3.Value;
                //lblMustInput.Visible = false;  --alter by hzx,on 20090206
                btnMoreQualification.Visible = false;
            }
            else if (AREntryStaffInfo["EventPersonTypeID"].ToString() == "4")
            {
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/SOM/StaffType_AddHoc.gif";
                this.imgStaffType.ToolTip = hdnStaffTypeTooltip4.Value;
                //lblMustInput.Visible = false;  --alter by hzx,on 20090206
                btnMoreQualification.Visible = false;
            }
            else
            {
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
            }
        }

        /// <summary>
        /// Setting Page By StationEventAmendTime
        /// </summary>
        /// <param name="AREntryStationEventAdmRegReader"></param>
        private void SettingPageByStationEventAmendTime(SqlDataReader ARStationEventAmendTimeReader, int TimeType)
        {
            if (ARStationEventAmendTimeReader.HasRows)
            {
                if (TimeType == 1)
                {
                    //update by benson 2015.07.27  U102 begin
                    //hdnChangeArrivalReason.Value = ARStationEventAmendTimeReader["Reason"].ToString();
                    //txtChangeArrivalReason.Text = ARStationEventAmendTimeReader["Reason"].ToString();
                    //delete by gordon 20150812
                    //if (!string.IsNullOrEmpty(ARStationEventAmendTimeReader["Reason"].ToString()))
                    //{
                    //    btnDepartureAmend.BackColor = System.Drawing.Color.Red;
                    //}
                    //update by benson 2015.07.27  U102 end
                }
                else if (TimeType == 2)
                {
                    hdnChangeDepartReason.Value = ARStationEventAmendTimeReader["Reason"].ToString();
                    //add by gordon 20150812
                    if (!string.IsNullOrEmpty(ARStationEventAmendTimeReader["Reason"].ToString()))
                    {
                        //btnDepartureAmend.BackColor = System.Drawing.Color.Red;
                        this.btnDepartureAmend.Visible = true;
                        this.btnDepartureAmend.Enabled = true;
                        this.btnDepartureAmend.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }
        }

        /// <summary>
        /// Setting Page By StationEventAdmReg
        /// </summary>
        /// <param name="AREntryStationEventAdmRegReader"></param>
        private void SettingPageByStationEventAdmReg(SqlDataReader AREntryStationEventAdmRegReader)
        {
            hdnStationEventAdmRegID.Value = AREntryStationEventAdmRegReader["StationEventAdmRegID"].ToString();
            if (AREntryStationEventAdmRegReader["EventNoOfWorkers"] != DBNull.Value)
            {
                txtPersonNumber.Text = AREntryStationEventAdmRegReader["EventNoOfWorkers"].ToString();
            }
            else
            {
                txtPersonNumber.Text = string.Empty;
            }
            if (AREntryStationEventAdmRegReader["AdmRegCategoryID"] != DBNull.Value)
            {
                this.FindByValueAndSelect(ddlWorkCategory, AREntryStationEventAdmRegReader["AdmRegCategoryID"].ToString());
                ddlWorkCategory_SelectedIndexChanged(null, EventArgs.Empty);
                //ddlWorkCategory.Items.FindByValue(AREntryStationEventAdmRegReader["AdmRegCategoryID"].ToString()).Selected=true;
                int nAdmRegCategoryID = Convert.ToInt32(AREntryStationEventAdmRegReader["AdmRegCategoryID"].ToString());
                CheckWorkCategorySignatureMust(nAdmRegCategoryID);
            }
            if (AREntryStationEventAdmRegReader["AdmRegSubCategoryID"] != DBNull.Value)
            {
                this.FindByValueAndSelect(ddlSubCategory, AREntryStationEventAdmRegReader["AdmRegSubCategoryID"].ToString());
                //ddlSubCategory.Items.FindByValue(AREntryStationEventAdmRegReader["AdmRegSubCategoryID"].ToString()).Selected=true;
                int nWorkSubCategoryID = Convert.ToInt32(AREntryStationEventAdmRegReader["AdmRegSubCategoryID"].ToString());
                CheckWorkSubCategorySignatureMust(nWorkSubCategoryID);
            }
            txtTNNumber.Text = AREntryStationEventAdmRegReader["TNNo"].ToString();
            txtTransactionNumber.Text = AREntryStationEventAdmRegReader["TransactionNo"].ToString();
            txtPossessionCertNo.Text = AREntryStationEventAdmRegReader["PossCertNo"].ToString();
            txtJobNature.Text = AREntryStationEventAdmRegReader["JobNature"].ToString();
            txtJobLocation.Text = AREntryStationEventAdmRegReader["JobLocation"].ToString();
            txtJobProtection.Text = AREntryStationEventAdmRegReader["JobProtection"].ToString();
            txtSupplement.Text = AREntryStationEventAdmRegReader["Remark"].ToString();
            if (AREntryStationEventAdmRegReader["ECSStatus1"] != DBNull.Value)
            {
                int nIndex = Convert.ToInt32(AREntryStationEventAdmRegReader["ECSStatus1"].ToString()) - 1;
                //rblEngineControlSystemFirst.Items[nIndex].Selected = true;
                //rblEngineControlSystemFirst.Items[nIndex].Attributes.Add("myDefaultValue", "true");
                if (nIndex == 1)
                {
                    rblEngineControlSystemFirst1.Checked = true;
                    rblEngineControlSystemFirst1.Attributes.Add("Value", AREntryStationEventAdmRegReader["ECSStatus1"].ToString());

                    //rblEngineControlSystemFirst1.Attributes.Add("myDefaultValue", "false");
                }
                else
                {
                    rblEngineControlSystemFirst0.Checked = true;
                    rblEngineControlSystemFirst0.Attributes.Add("Value", AREntryStationEventAdmRegReader["ECSStatus1"].ToString());
                    //rblEngineControlSystemFirst0.Attributes.Add("myDefaultValue", "false");
                }

                //rblEngineControlSystemFirst.Items[nIndex].Value = AREntryStationEventAdmRegReader["ECSStatus1"].ToString();
            }

            if (AREntryStationEventAdmRegReader["ECSStatus2"] != DBNull.Value)
            {
                int nIndex = Convert.ToInt32(AREntryStationEventAdmRegReader["ECSStatus2"].ToString()) - 1;
                //rblEngineControlSystemSecond.Items[nIndex].Selected = true;
                //rblEngineControlSystemSecond.Items[nIndex].Attributes.Add("myDefaultValue", "true");
                if (nIndex == 1)
                {
                    rblEngineControlSystemSecond1.Checked = true;
                    rblEngineControlSystemSecond1.Attributes.Add("Value", AREntryStationEventAdmRegReader["ECSStatus2"].ToString());
                }
                else
                {
                    rblEngineControlSystemSecond0.Checked = true;
                    rblEngineControlSystemSecond0.Attributes.Add("Value", AREntryStationEventAdmRegReader["ECSStatus2"].ToString());
                }
                //rblEngineControlSystemSecond.Items[nIndex].Value = AREntryStationEventAdmRegReader["ECSStatus2"].ToString();
            }

            if (AREntryStationEventAdmRegReader["ECSStatus3"] != DBNull.Value)
            {
                int nIndex = Convert.ToInt32(AREntryStationEventAdmRegReader["ECSStatus3"].ToString()) - 1;
                //rblEngineControlSystemThird.Items[nIndex].Selected = true;
                //rblEngineControlSystemThird.Items[nIndex].Attributes.Add("myDefaultValue","true");
                if (nIndex == 1)
                {
                    rblEngineControlSystemThird1.Checked = true;
                    rblEngineControlSystemSecond1.Attributes.Add("Value", AREntryStationEventAdmRegReader["ECSStatus3"].ToString());
                }
                else
                {
                    rblEngineControlSystemThird0.Checked = true;
                    rblEngineControlSystemThird0.Attributes.Add("Value", AREntryStationEventAdmRegReader["ECSStatus3"].ToString());
                }
                //rblEngineControlSystemThird.Items[nIndex].Value = AREntryStationEventAdmRegReader["ECSStatus3"].ToString();
            }

        }

        private List<string> GetQual()
        {
            List<string> qualList = new List<string>();
            string qualTypeCode = CommonData.GetStrVal("SOM_CQAQual_QualTypeCode").Trim();
            DataSet ds_CQA = MTRC.ODMS.DAL.SOM.CodeSetup.CdStaffInfo.GetCQASData(txtStaffID.Text, qualTypeCode);
            DataTable dt_CQA = ds_CQA.Tables[0];
            foreach (DataRow rowItem in dt_CQA.Rows)
            {
                if (!qualList.Contains(rowItem["QUALCD"].ToString() + " " + rowItem["QUALSHORTDESC"].ToString()))
                {
                    qualList.Add(rowItem["QUALCD"].ToString() + " " + rowItem["QUALSHORTDESC"].ToString());
                }
            }

            return qualList;
        }

        /// <summary>
        /// Setting Page By StationEventPersonQual.     updata by hzx,on 20090115 for iusue 0907
        /// </summary>
        /// <param name="PersonHoldQual"></param>
        private void SettingPageByStationEventPersonQual(DataTable PersonHoldQual, bool IsTransfer)
        {
            if (!IsTransfer)
            {
                if (PersonHoldQual.Columns.Contains("Qualification"))
                {
                    DataColumn dc = PersonHoldQual.Columns["Qualification"];
                    dc.ColumnName = "QualCode";
                }
                List<string> listQualification = new List<string>();
                if (hdnStaffType.Value.ToString().Trim() == "1" || hdnStaffType.Value.ToString().Trim() == "2")
                {
                    string sCharacter = CommonData.GetCharVal("SOM_AR_QualificationDelimiterCharacter").ToString();
                    string strQualification = string.Empty;
                    /* update by jack 20150706 for u50.2 */
                    //if (PersonHoldQual.Rows.Count > 0) {
                    //    for (int i = 0; i < PersonHoldQual.Rows.Count; i++) {
                    //        strQualification += PersonHoldQual.Rows[i]["QualCode"].ToString() + "-" + PersonHoldQual.Rows[i]["QualDesc"].ToString() + sCharacter;
                    //    }
                    //    strQualification = strQualification.Remove(strQualification.Length - 1, 1);
                    //}
                    //txtQualification.Text = strQualification;
                    if (PersonHoldQual.Rows.Count > 0 && this.newQualification.Style["display"] == "none" && this.oldQualification.Style["display"] == "block")
                    {
                        for (int i = 0; i < PersonHoldQual.Rows.Count; i++)
                        {
                            strQualification += PersonHoldQual.Rows[i]["QualCode"].ToString() + "-" + PersonHoldQual.Rows[i]["QualDesc"].ToString() + sCharacter;
                        }
                        strQualification = strQualification.Remove(strQualification.Length - 1, 1);
                        txtQualification.Text = strQualification;
                        //listQualification.Add(strQualification);
                        //BindQualification(listQualification);
                    }
                    else
                    {
                        txtQualification.Text = string.Empty;
                    }

                    /* update by jack 20150706 for u50.2 */
                    //if (PersonHoldQual.Rows.Count > 0 && CommonData.GetCharVal("SOM_CQAQual_Realtime_Enable").Trim() == "Y")
                    if (PersonHoldQual.Rows.Count > 0 && this.newQualification.Style["display"] == "block" && this.oldQualification.Style["display"] == "none")
                    {

                        DataTable dtQualMas = CDQualMas.GetAllCDQualMas().Tables[0];

                        //DataRow[] dr = dtQualMas.Select("QualCode='" + PersonHoldQual.Rows[0]["QualCode"].ToString() + "'");
                        //string qualDesc = string.Empty;
                        //if (dr.Length > 0)
                        //{
                        //    qualDesc = dr[0]["QualDesc"].ToString();
                        //}
                        //listQualification.Add((PersonHoldQual.Rows[0]["QualCode"].ToString() + " " + qualDesc).Trim());
                        //BindQualification(listQualification);
                        //dtQualMas.Dispose();
                        string qualification = string.Empty;
                        for (int i = 0; i < PersonHoldQual.Rows.Count; i++)
                        {
                            DataRow[] dr = dtQualMas.Select("QualCode='" + PersonHoldQual.Rows[i]["QualCode"].ToString() + "'");
                            string qualDesc = string.Empty;
                            if (dr.Length > 0)
                            {
                                qualDesc = dr[0]["QualDesc"].ToString();
                            }
                            qualification += PersonHoldQual.Rows[i]["QualCode"].ToString() + " " + qualDesc + sCharacter;
                        }
                        qualification = qualification.Remove(qualification.Length - 1, 1);
                        listQualification.Add(qualification);
                        BindQualification(listQualification);
                        dtQualMas.Dispose();
                    }
                    else
                    {
                        ddlQualification.Items.Clear();
                        ListItem item = new ListItem();
                        item.Text = this.GetMessage("SOM_QualificationNotFound");
                        item.Value = "";
                        ddlQualification.Items.Add(item);
                        ddlQualification.SelectedIndex = 0;
                    }
                    /*************************************/
                    //delete by gordon 20150826 U168.9
                    //Qualification Enabled Logic not needed for now
                    ////add by gordon 20150818
                    //if (hdnStatus.Value == "1")
                    //{
                    //    List<string> qualSource = GetQual();
                    //    string listItemString = "";
                    //    if (qualSource.Count > 0)
                    //    {
                    //        string qualification = string.Empty;
                    //        foreach (string qual in qualSource)
                    //        {
                    //            if (qual.StartsWith(ddlQualification.SelectedItem.Text.Split(' ')[0].ToString()))
                    //            {
                    //                ddlQualification.Items.Remove(ddlQualification.SelectedItem);
                    //                listItemString = qual;
                    //                break;
                    //            }
                    //        }

                    //        if (string.IsNullOrEmpty(listItemString))
                    //        {
                    //            ddlQualification.Items.Clear();
                    //        }

                    //        if (string.IsNullOrEmpty(ddlQualification.SelectedValue))
                    //        {
                    //            ddlQualification.Items.Remove(ddlQualification.SelectedItem);
                    //        }

                    //        ddlQualification.Items.Add(new ListItem("", ""));
                    //        foreach (string qual in qualSource)
                    //        {
                    //            ddlQualification.Items.Add(new ListItem(qual, qual));
                    //        }

                    //        //if (listItemString != "")
                    //        {
                    //            ListItem li = ddlQualification.Items.FindByText(listItemString);
                    //            li.Selected = true;
                    //        }
                    //    }
                    //}
                }
                else
                {
                    txtQualification.Text = string.Empty;
                    ddlQualification.Items.Clear();
                    ListItem item = new ListItem();
                    item.Text = this.GetMessage("SOM_QualificationNotFound");
                    item.Value = "";
                    ddlQualification.Items.Add(item);
                    ddlQualification.SelectedIndex = 0;
                    //BindQualification(listQualification);
                }
            }
            else
            {
                string sCharacter = CommonData.GetCharVal("SOM_AR_QualificationDelimiterCharacter").ToString();
                string strQualification = string.Empty;
                if (PersonHoldQual.Rows.Count > 0 && this.newQualification.Style["display"] == "none" && this.oldQualification.Style["display"] == "block")
                {
                    for (int i = 0; i < PersonHoldQual.Rows.Count; i++)
                    {
                        strQualification += PersonHoldQual.Rows[i]["QualCode"].ToString() + "-" + PersonHoldQual.Rows[i]["QualDesc"].ToString() + sCharacter;
                    }
                    strQualification = strQualification.Remove(strQualification.Length - 1, 1);
                    txtQualification.Text = strQualification;
                }
                else
                {
                    txtQualification.Text = string.Empty;
                }
            }
        }

        /// <summary>
        /// setting  Signature control by StationEventSign table
        /// </summary>
        /// <param name="StationEventSignReader"></param>
        /// <param name="EventSignType"></param>
        private void SettingPageByStationEventSignReader(SqlDataReader StationEventSignReader, int EventSignType)
        {
            if (StationEventSignReader.HasRows)
            {
                int nsignType = Convert.ToInt32(StationEventSignReader["SignType"].ToString());
                if (EventSignType == 1)
                {
                    hdnStationEventSignID.Value = StationEventSignReader["StationEventSignID"].ToString();
                    hdnSignatureTypeArrive.Value = StationEventSignReader["SignType"].ToString();
                    hdnSignatureNameArrive.Value = StationEventSignReader["SignFileName"].ToString();
                 
                    //modify by tim for save signature to database
                    string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival+ "_" + ODMUserID;
                    if (!string.IsNullOrEmpty(StationEventSignReader["SignFileImage"].ToString()))
                    {
                        Session[signatureName] = (byte[])StationEventSignReader["SignFileImage"];
                    }
                    else
                    {
                        Session[signatureName] = null;
                    }
                   

                    //update by benson 2015.07.27  U102  begin
                    this.ucSignatureNew1.InitUCSignatureValue(1, nsignType, StationEventSignReader["SignFileName"].ToString().Trim());
                    //ucSignatureArrivalBottom.InitUCSignatureValue(1, nsignType, StationEventSignReader["SignFileName"].ToString().Trim());
                    //update by benson 2015.07.27  U102  end
                }
                else if (EventSignType == 2)
                {
                    hdnStationEventCompleteSignID.Value = StationEventSignReader["StationEventSignID"].ToString();
                    hdnSignatureTypeDepart.Value = StationEventSignReader["SignType"].ToString();
                    hdnSignatureNameDepart.Value = StationEventSignReader["SignFileName"].ToString();
                    //modify by tim for save signature to database
                    string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Departure + "_" + ODMUserID;
                    //Session[signatureName] = (byte[])StationEventSignReader["SignFileImage"];
                    if (!string.IsNullOrEmpty(StationEventSignReader["SignFileImage"].ToString()))
                    {
                        Session[signatureName] = (byte[])StationEventSignReader["SignFileImage"];
                    }
                    else
                    {
                        Session[signatureName] = null;
                    }
                    //update by benson 2015.07.27  U102  begin
                    //this.ucSignatureNew1.InitUCSignatureValue(2, nsignType, StationEventSignReader["SignFileName"].ToString().Trim());
                    //ucSignatureNew1.SetEnable(true, 2);
                    //ucSignatureDepartureBottom.InitUCSignatureValue(2, nsignType, StationEventSignReader["SignFileName"].ToString().Trim());
                    //ucSignatureDepartureBottom.SetEnable(true, 2, true);
                    //update by benson 2015.07.27  U102  end
                }
            }
        }

        /// <summary>
        /// Setting Page By CDECSStatus
        /// </summary>
        /// <param name="drCDECSStatusReader"></param>
        /// <param name="Type"></param>
        private void SettingPageByCDECSStatusReader(SqlDataReader drCDECSStatusReader, int Type)
        {
            if (drCDECSStatusReader.HasRows)
            {
                if (Type == 1)
                {
                    //rblEngineControlSystemFirst.Items[0].Value = drCDECSStatusReader["ECSStatusID"].ToString();
                    rblEngineControlSystemFirst0.Attributes.Add("Value", drCDECSStatusReader["ECSStatusID"].ToString());

                    //rblEngineControlSystemSecond.Items[0].Value = drCDECSStatusReader["ECSStatusID"].ToString();
                    rblEngineControlSystemSecond0.Attributes.Add("Value", drCDECSStatusReader["ECSStatusID"].ToString());

                    //rblEngineControlSystemThird.Items[0].Value = drCDECSStatusReader["ECSStatusID"].ToString();
                    rblEngineControlSystemThird0.Attributes.Add("Value", drCDECSStatusReader["ECSStatusID"].ToString());

                    //rblEngineControlSystemFirst.Items[0].Text = drCDECSStatusReader["Description"].ToString();
                    rblEngineControlSystemFirst0.Text = drCDECSStatusReader["Description"].ToString();

                    //rblEngineControlSystemSecond.Items[0].Text = drCDECSStatusReader["Description"].ToString();
                    rblEngineControlSystemSecond0.Text = drCDECSStatusReader["Description"].ToString();

                    //rblEngineControlSystemThird.Items[0].Text = drCDECSStatusReader["Description"].ToString();
                    rblEngineControlSystemThird0.Text = drCDECSStatusReader["Description"].ToString();

                }
                else if (Type == 2)
                {
                    //rblEngineControlSystemFirst.Items[1].Value = drCDECSStatusReader["ECSStatusID"].ToString();
                    rblEngineControlSystemFirst1.Attributes.Add("Value", drCDECSStatusReader["ECSStatusID"].ToString());

                    //rblEngineControlSystemSecond.Items[1].Value = drCDECSStatusReader["ECSStatusID"].ToString();
                    rblEngineControlSystemSecond1.Attributes.Add("Value", drCDECSStatusReader["ECSStatusID"].ToString());

                    //rblEngineControlSystemThird.Items[1].Value = drCDECSStatusReader["ECSStatusID"].ToString();
                    rblEngineControlSystemThird1.Attributes.Add("Value", drCDECSStatusReader["ECSStatusID"].ToString());

                    //rblEngineControlSystemFirst.Items[1].Text = drCDECSStatusReader["Description"].ToString();
                    rblEngineControlSystemFirst1.Text = drCDECSStatusReader["Description"].ToString();

                    //rblEngineControlSystemSecond.Items[1].Text = drCDECSStatusReader["Description"].ToString();
                    rblEngineControlSystemSecond1.Text = drCDECSStatusReader["Description"].ToString();

                    //rblEngineControlSystemThird.Items[1].Text = drCDECSStatusReader["Description"].ToString();
                    rblEngineControlSystemThird1.Text = drCDECSStatusReader["Description"].ToString();


                }
            }
        }

        /// <summary>
        /// Setting Fire Grid,Data Bind
        /// </summary>
        private void SettingFireGridByDataBind()
        {
            if (this.SaveModel == 1)
            {
                if (hdnFireSystemKey.Value != string.Empty)
                {
                    int nFireSystemKey = Convert.ToInt32(hdnFireSystemKey.Value);
                    DataTable dtFireGridList = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.GetFireGridListByKey(nFireSystemKey, this.LangCode);
                    grdFireSystem.DataSource = dtFireGridList.DefaultView;
                    grdFireSystem.DataBind();
                }
                else
                {
                    grdFireSystem.DataSource = new DataTable().DefaultView;
                    grdFireSystem.DataBind();
                }
            }
            else
            {
                if (chkObsolete.Checked == true)
                {
                    chkObsolete_CheckedChanged(null, null);
                }
                else
                {
                    if (hdnFireSystemKey.Value == string.Empty)
                    {
                        //1:AR;2:asset loan; 3:fire
                        //Update by jack 20151127 U263 use odmuser.usergroupid instead of stored procedure
                        //string xml = BLL.SOM.Event.FireProtection.CreateDataSetXml(this.LangCode, this.StationEventID);
                        string xml = BLL.SOM.Event.FireProtection.CreateDataSetXml(this.LangCode, this.StationEventID, this.ODMUser.UserGroupID.ToString());
                        //End update by jack 20151127 U263 use odmuser.usergroupid instead of stored procedure
                        int tempID = DAL.SOM.TempData.AddTempData(this.ODMUser.ID, this.ODMUser.Domain, xml);
                        //add by gordon 20150811 U147
                        CurrentTempID = tempID;

                        //tempID = 5201;
                        hdnFireSystemKey.Value = tempID.ToString();
                        DataTable dtFireGridList = BLL.SOM.Event.StationEventAdmReg.GetFireGridListByKey(tempID, this.LangCode);
                        DataView dvBind = new DataView();
                        dvBind.Table = dtFireGridList;
                        dvBind.RowFilter = "FlagObsolete=0";
                        grdFireSystem.DataSource = dvBind;
                        grdFireSystem.DataBind();
                    }
                    else
                    {
                        int nFireSystemKey = Convert.ToInt32(hdnFireSystemKey.Value);
                        //add by gordon 20150811 U147
                        CurrentTempID = nFireSystemKey;
                        DataTable dtFireGridList = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.GetFireGridListByKey(nFireSystemKey, this.LangCode);
                        DataView dvBind = new DataView();
                        dvBind.Table = dtFireGridList;
                        dvBind.RowFilter = "FlagObsolete=0";
                        grdFireSystem.DataSource = dvBind;
                        grdFireSystem.DataBind();
                    }
                }
            }
        }

        /// <summary>
        /// Get AssetLoan data and bind
        /// </summary>
        private void SettingAssetLoanGridByData()
        {
            DataTable dtAssetLoanEventIDList = new DataTable();
            if (hdnAssetLoanMainDataTmpID.Value.Trim() == string.Empty)
            {
                //1:AR;2:asset loan; 3:fire
                ////dtAssetLoanEventIDList = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.GetChildStationEventIDList(this.StationEventID, 2, this.LangCode);----//huangyao: Change 0375--20081105
                //ODMUser.StationID no longer use in store proc | Gordon 20151020 U247
                //Comment by gordon 20160215 ISU51
                ////add by gordon 20160201 ISU12
                //Log.Logger("Get AssetLoan Grid List Start", 4, ODMUser.ID, ODMUser.UserGroupName);
                //Log.Logger("Station Event ID:" + StationEventID, 4, ODMUser.ID, ODMUser.UserGroupName);
                ////add end by gordon 20160201
                //Comment end by gordon 20160215 ISU51
                dtAssetLoanEventIDList = MTRC.ODMS.DAL.SOM.Event.StationEventAssetLoanItemDa.GetAssetLoanItemByStationEventID(0, this.ODMUser.StationID, this.LangCode, this.StationEventID); //--//huangyao: Change 0375--20081105
                grdAssetLoan.DataSource = dtAssetLoanEventIDList.DefaultView;
                grdAssetLoan.DataBind();
            }
            else
            {
                //----//huangyao: Change 0375--20081105
                //int nAssetLoanKey = Convert.ToInt32(hdnAssetLoanMainDataTmpID.Value);
                int nAssetLoanKey = Convert.ToInt32(hdnAssetLoanItemDataTmpID.Value);
                //Comment by gordon 20160215 ISU51
                ////add by gordon 20160201 ISU12
                //Log.Logger("Get AssetLoan Grid List Start", 4, ODMUser.ID, ODMUser.UserGroupName);
                //Log.Logger("nAssetLoanKey:" + nAssetLoanKey, 4, ODMUser.ID, ODMUser.UserGroupName);
                ////add end by gordon 20160201
                //Comment end by gordon 20160215 ISU51
                dtAssetLoanEventIDList = BLL.SOM.TempData.GetCacheData(nAssetLoanKey).Tables[0];

                foreach (DataRow dr in dtAssetLoanEventIDList.Rows)
                {
                    if (MTRC.ODMS.DAL.COM.Util.StringFromDB(dr["EventNo"]) == string.Empty)
                    {
                        //dr["EventNo"] = this.GetLabel("SOM_EventNoForTempDataInAR"); //huangyao 20081127 modifiy in MTR office
                        dr["EventNo"] = ""; //huangyao 20081127 modifiy in MTR office
                        dr["EventStatusID"] = 1;
                        dr["HighLight"] = 0;
                    }
                }

                if (dtAssetLoanEventIDList.Rows.Count > 0)
                {
                    this.grdAssetLoan.Enabled = true;
                }

                //if (dtAssetLoanEventIDList.Rows.Count > 0 && MTRC.ODMS.DAL.COM.Util.StringFromDB(dtAssetLoanEventIDList.Rows[0]["EventNo"]) == string.Empty)
                //{
                //    dtAssetLoanEventIDList.Rows[0]["EventNo"] = this.GetLabel("SOM_EventNoForTempDataInAR");
                //    dtAssetLoanEventIDList.Rows[0]["EventStatusID"] = 1;
                //    dtAssetLoanEventIDList.Rows[0]["HighLight"] = 0;
                //    this.grdAssetLoan.Enabled = true;
                //}

                grdAssetLoan.DataSource = dtAssetLoanEventIDList.DefaultView;
                grdAssetLoan.DataBind();
            }

            if (dtAssetLoanEventIDList.Rows.Count != 0)
            {
                btnAddNewAssetLoan.Enabled = false;
                initAssetLoan(dtAssetLoanEventIDList);
            }
        }
        //add by benson 2015-09-15 begin
        private void initAssetLoan(DataTable dtAssetLoanEventIDList)
        {
            string strParentStationEventID = this.StationEventID.ToString();
            string strStationEventID = "";
            string strAction = "Edit";
            string strIsPageAllReadOnly = "0";
            if (this.ReadOnly)
            {
                strIsPageAllReadOnly = "1";
            }
            string strIsOpenFromAR = "1";
            //----added by huangyao
            int assetLoanDataTmpID = -1;
            int.TryParse(this.hdnAssetLoanMainDataTmpID.Value.Trim(), out assetLoanDataTmpID);
            int assetLoanItemDataTmpID = -1;
            int.TryParse(this.hdnAssetLoanItemDataTmpID.Value.Trim(), out assetLoanItemDataTmpID);


            foreach (DataRow dr in dtAssetLoanEventIDList.Rows)
            {
                if (!string.IsNullOrEmpty(dr["StationEventID"].ToString()))
                {
                    lblALEventNumber.Text = dr["EventNo"].ToString();

                    if (dr["EventStatusID"].ToString() == "1")
                    {
                        imgALStatus.ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_OS.gif";
                    }
                    else if (dr["EventStatusID"].ToString() == "2")
                    {
                        imgALStatus.ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_COM.gif";
                    }
                    else
                    {
                        imgALStatus.ImageUrl = Request.ApplicationPath.ToString() + "/Images/SOM/EventStatus_Void.gif";
                    }
                    imgALStatus.ToolTip = dr["CDES_Description"].ToString();

                    //update by benson 2015.08.27 u183.3 begin
                    if (dr["EventStatusID"].ToString() == "2")
                    {
                        imgALHighLight.ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                        imgALHighLight.ToolTip = this.GetLabel("SOM_HighLightNormal", false);
                    }
                    //update by benson 2015.08.27 u183.3 end
                    else if (dr["HighLight"].ToString() == "1")
                    {
                        imgALHighLight.ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Yellow.gif";
                        imgALHighLight.ToolTip = this.GetLabel("SOM_HighLightYellow", false);
                    }
                    else if (dr["HighLight"].ToString() == "2")
                    {
                        imgALHighLight.ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Red.gif";
                        imgALHighLight.ToolTip = this.GetLabel("SOM_HighLightRed", false);
                    }
                    else
                    {
                        imgALHighLight.ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                        imgALHighLight.ToolTip = this.GetLabel("SOM_HighLightNormal", false);
                    }

                    strStationEventID = dr["StationEventID"].ToString();

                }
            }
            if (dtAssetLoanEventIDList.Rows.Count > 0)
            {
                btnALEdit.Visible = true;
                string strURL = "../Popup/PopupARAssetLoan.aspx?ParentStationEventID=" + strParentStationEventID + "&StationEventID=" + strStationEventID + "&Action=" + strAction + "&IsPageAllReadOnly=" + strIsPageAllReadOnly + "&IsOpenFromAR=" + strIsOpenFromAR + "&MenuID=" + this.MenuID + "&AssetLoanMainDataTmpID=" + assetLoanDataTmpID.ToString() + "&AssetLoanItemDataTmpID=" + assetLoanItemDataTmpID.ToString();
                btnALEdit.Attributes.Add("onclick", "javascript:return OpenPopupARAssetLoan('" + strURL + "');");
            }

        }
        //add by benson 2015-09-15 end

        /// <summary>
        /// Check Work Category whether must Signature or not
        /// </summary>
        /// <param name="WorkCategoryID"></param>
        /// <returns>1:must signature;0:not must</returns>
        private void CheckWorkCategorySignatureMust(int WorkCategoryID)
        {
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drARAdmRegCategoryByID = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARAdmRegCategoryByIDReader(this.LangCode, WorkCategoryID))
            {
                drARAdmRegCategoryByID.Read();
                if (drARAdmRegCategoryByID.HasRows)
                {
                    if (Convert.ToBoolean(drARAdmRegCategoryByID["FlagProtect"]))
                    {
                        ViewState["FlagProtect"] = "1";
                    }
                    else
                    {
                        ViewState["FlagProtect"] = "0";
                    }
                    if (Convert.ToBoolean(drARAdmRegCategoryByID["FlagReqSign"]))
                    {
                        ViewState["FlagReqSign"] = "1";
                    }
                    else
                    {
                        ViewState["FlagReqSign"] = "0";
                    }
                }
                else
                {
                    ViewState["FlagProtect"] = "0";
                    ViewState["FlagReqSign"] = "0";
                }
            }

            //update by gordon 20150827 U168.10
            //if (ViewState["FlagReqSign"].ToString() == "1" || ViewState["SubFlagReqSign"].ToString() == "1")
            if ((ViewState["FlagReqSign"].ToString() == "1" || ViewState["SubFlagReqSign"].ToString() == "1") && btnDeparture.Enabled)
            {
                imgSignatureRequired.ImageUrl = Request.ApplicationPath + "/Images/SOM/MustSignature.gif";
                if (this.SaveModel == 2)
                {
                    //update by benson 2015.07.27  U102 begin
                    //if (this.ucSignatureDeparture.GetSignatureFullFileName(2).ToString() != string.Empty)
                    //{
                    //    //ucSignatureDeparture.SetEnable(true, 2, true);
                    //    //ucSignatureDepartureBottom.SetEnable(true, 2, true);
                    //}
                    //else
                    //{
                    //    //ucSignatureDeparture.SetEnable(true, 2, false);
                    //    //ucSignatureDepartureBottom.SetEnable(true, 2, false);
                    //}
                    //update by benson 2015.07.27  U102 end
                }
            }
            else
            {
                imgSignatureRequired.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
                //update by benson 2015.07.27  U102 begin
                //if (ucSignatureDeparture.GetSignatureFullFileName(2).ToString() != string.Empty)
                //{
                //    ucSignatureDeparture.SetEnable(false, 2, true);
                //    ucSignatureDepartureBottom.SetEnable(false, 2, true);
                //}
                //else
                //{
                //    ucSignatureDeparture.SetEnable(false, 2, false);
                //    ucSignatureDepartureBottom.SetEnable(false, 2, false);
                //}
                //update by benson 2015.07.27  U102 begin
            }
        }

        /// <summary>
        /// Check Work Sub Category whether must Signature or not 
        /// </summary>
        /// <param name="WorkSubCategoryID"></param>
        /// <returns>1:must signature;0:not must</returns>
        private void CheckWorkSubCategorySignatureMust(int WorkSubCategoryID)
        {
            //edit by hjh 20120519 for DataReader not close
            using (SqlDataReader drARAdmRegSubCategoryByID = ODMS.BLL.SOM.Event.StationEventAdmReg.GetARAdmRegSubCategoryByIDReader(this.LangCode, WorkSubCategoryID))
            {
                drARAdmRegSubCategoryByID.Read();
                if (drARAdmRegSubCategoryByID.HasRows)
                {
                    if ((Convert.ToBoolean(drARAdmRegSubCategoryByID["FlagProtect"])))
                    {
                        ViewState["SubFlagProtect"] = "1";
                    }
                    else
                    {
                        ViewState["SubFlagProtect"] = "0";
                    }
                    if (Convert.ToBoolean(drARAdmRegSubCategoryByID["FlagReqSign"]))
                    {
                        ViewState["SubFlagReqSign"] = "1";
                    }
                    else
                    {
                        ViewState["SubFlagReqSign"] = "0";
                    }
                }
                else
                {
                    ViewState["SubFlagProtect"] = "0";
                    ViewState["SubFlagReqSign"] = "0";
                }
            }

            //update by gordon 20150827 U168.10
            //if (ViewState["FlagReqSign"].ToString() == "1" || ViewState["SubFlagReqSign"].ToString() == "1")
            if ((ViewState["FlagReqSign"].ToString() == "1" || ViewState["SubFlagReqSign"].ToString() == "1") && btnDeparture.Enabled)
            {
                imgSignatureRequired.ImageUrl = Request.ApplicationPath + "/Images/SOM/MustSignature.gif";
                if (this.SaveModel == 2)
                {
                    //update by benson 2015.07.27  U102 begin
                    //if (ucSignatureDeparture.GetSignatureFullFileName(2).ToString() != string.Empty)
                    //{
                    //    ucSignatureDeparture.SetEnable(true, 2, true);
                    //    ucSignatureDepartureBottom.SetEnable(true, 2, true);
                    //}
                    //else
                    //{
                    //    ucSignatureDeparture.SetEnable(true, 2, false);
                    //    ucSignatureDepartureBottom.SetEnable(true, 2, false);
                    //}
                    //update by benson 2015.07.27  U102 begin
                }
            }
            else
            {
                imgSignatureRequired.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
                //update by benson 2015.07.27  U102 begin
                //if (ucSignatureDeparture.GetSignatureFullFileName(2).ToString() != string.Empty)
                //{
                //    ucSignatureDeparture.SetEnable(false, 2, true);
                //    ucSignatureDepartureBottom.SetEnable(false, 2, true);
                //}
                //else
                //{
                //    ucSignatureDeparture.SetEnable(false, 2, false);
                //    ucSignatureDepartureBottom.SetEnable(false, 2, false);
                //}
                //update by benson 2015.07.27  U102 end
            }
        }

        /// <summary>
        /// save data
        /// </summary>
        private int Save(string RequirePasswordUserID, int RequirePasswordStaffInfoID)
        {
            //add by jack 20150707 for U50
            if (CommonData.GetCharVal("SOM_CQAQual_Realtime_Enable").Trim() == "Y")
            {
                SaveQualificationToTempData();
            }

            StationEventInfo StationEventModel = new StationEventInfo();
            if (this.SaveModel == 1)//create or insert
            {
                StationEventModel.StationEventID = 0;
                StationEventModel.EventNo = string.Empty;
                StationEventModel.EventStatusID = 1;
                StationEventModel.HighLight = 0;
                //update by benson 2015-10-24 u253 begin
                //StationEventModel.EventTime = this.dtbArrivalTime.GetDateTime();
                //update by benson 2015-10-24 u253 end
            }
            else
            {
                StationEventModel.StationEventID = this.StationEventID;
                StationEventModel.EventNo = lblRegistryNumber.Text;
                StationEventModel.EventStatusID = Convert.ToInt32(hdnStatus.Value);
                StationEventModel.HighLight = Convert.ToInt32(hdnHighLight.Value);
                ////update by benson 2015-10-24 u253 begin
                //StationEventModel.EventTime = this.ConvertToDateTime(lblArrivalTime.Text.Trim());
                ////update by benson 2015-10-24 u253 end
            }
            //update by gordon U247
            //StationEventModel.LocationID = this.ODMUser.StationID;
            StationEventModel.LocationID = this.ODMUser.LocationID;
            StationEventModel.EventTypeID = 1; //AdmissionRegistry
            StationEventModel.EventTime = this.ConvertToDateTime(lblArrivalTime.Text.Trim());
            StationEventModel.StationEventSignID = 0;
            if (txtEstimatedCompletionTime.Text.Trim() != string.Empty)
            {
                decimal hrs = 0;
                decimal.TryParse(txtEstimatedCompletionTime.Text.Trim(), out hrs);
                StationEventModel.EstimatedWrkHour = hrs;
            }
            //StationEventModel.EventCompleteTime = Convert.ToDateTime(lblShouldCompletionTime.Text.Trim());
            //StationEventModel.StationEventCompleteSignID = null;
            StationEventModel.AmendReason = string.Empty;
            StationEventModel.Description = string.Empty;
            StationEventModel.Remark = txtRemark.Text;
            //StationEventModel.ParentStationEventID = DBNull.Value;
            //StationEventModel.StationEventPersonID=null;
            //StationEventModel.DisplayOrder = null;
            StationEventModel.FlagHandover = chkHandoverCheck.Checked;
            StationEventModel.HandoverNote = txtHandoverCheckDetail.Text;
            //update by benson 2015-10-29 U269 begin
            if (this.SaveModel == 1)
            {
                StationEventModel.CreateUser = this.ODMUser.ID;
                StationEventModel.CreateTime = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime();
            }
            //update by benson 2015-10-29 U269 end
            StationEventModel.FlagObsolete = false;
            if (RequirePasswordUserID != string.Empty)
            {
                StationEventModel.RequirePasswordUserID = RequirePasswordUserID;
                StationEventModel.LastUpdUser = int.Parse(Session[BLL.COM.Session.COM_Validation_UserID].ToString());
                StationEventModel.ActingasUser = int.Parse(Session[BLL.COM.Session.COM_Validation_UserID].ToString());
            }
            else
            {
                StationEventModel.LastUpdUser = this.ODMUser.ID;
                StationEventModel.ActingasUser = this.ODMUser.ID;
            }
            if (RequirePasswordStaffInfoID != 0)
            {
                StationEventModel.RequirePasswordStaffInfoID = RequirePasswordStaffInfoID;
            }
            StationEventModel.LastUpdTime = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime();
            //use StationEventInfo

            //get StationEventPersonInfo
            StationEventPersonInfo StationEventPersonModel = new StationEventPersonInfo();
            if (this.SaveModel != 1 && hdnTransferResponsibilityKey.Value == string.Empty)
            {
                StationEventPersonModel = null;
            }
            else
            {
                if (this.SaveModel == 1)
                {
                    StationEventPersonModel.StationEventPersonID = 0;
                    StationEventPersonModel.StationEventID = 0;
                }
                else
                {
                    if (hdnTransferResponsibilityKey.Value != string.Empty)
                    {
                        StationEventPersonModel.StationEventPersonID = 0;
                        StationEventPersonModel.StationEventID = this.StationEventID;
                    }
                }
                //StationEventPersonModel.SequenceNo
                StationEventPersonModel.EventPersonTypeID = Convert.ToInt32(hdnStaffType.Value);
                if (Convert.ToInt32(hdnStaffType.Value) == 4) //temporary staff
                {
                    StationEventPersonModel.StaffOrExtPartyID = 0;
                    StationEventPersonModel.StaffID = this.txtStaffID.Text.Trim();
                    StationEventPersonModel.StaffName = this.txtStaffName.Text.Trim();
                    //StationEventPersonModel.Tel = this.txtContactNo.Text.Trim();
                    StationEventPersonModel.Company = txtDepartmentCompany.Text;
                }
                else
                {
                    int staffOrExtPartyID = 0;
                    int.TryParse(hdnStaffOrExtPartyID.Value.Trim(), out staffOrExtPartyID);
                    StationEventPersonModel.StaffOrExtPartyID = staffOrExtPartyID;
                    //update by jack 20150702 for U50.4
                    //StationEventPersonModel.StaffID = "";
                    //StationEventPersonModel.StaffName = "";
                    //StationEventPersonModel.Company = "";
                    if (Convert.ToInt32(hdnStaffType.Value) == 2)
                    {
                        StationEventPersonModel.StaffOrExtPartyID = null;
                    }
                    StationEventPersonModel.StaffID = this.txtStaffID.Text.Trim();
                    StationEventPersonModel.StaffName = this.txtStaffName.Text.Trim();

                    if (this.oldCompany.Style["display"] == "block")
                    {
                        StationEventPersonModel.Company = hdnDepartmentCompany.Value;
                    }
                    else
                    {
                        hdnDepartmentCompany.Value = this.txtSelectedOU.Value;
                        StationEventPersonModel.Company = hdnDepartmentCompany.Value;
                    }


                    //StationEventPersonModel.Tel = this.txtContactNo.Text.Trim();

                }
                StationEventPersonModel.Tel = this.txtContactNo.Text.Trim();
                StationEventPersonModel.ReqQual = "";

                //add new filed  by hzx 2009.01.04
                //ExtPartyStaffSnapShotID to to table SOM_StationEventPerson
                int nExtPartyStaffSnapShotID = 0;
                int.TryParse(this.hdnExtPartyStaffSnapShotID.Value.Trim(), out nExtPartyStaffSnapShotID);
                //update by jack 20150702 for U50.4
                //StationEventPersonModel.ExtPartyStaffSnapShotID = nExtPartyStaffSnapShotID;
                if (Convert.ToInt32(hdnStaffType.Value) == 2)
                {
                    StationEventPersonModel.ExtPartyStaffSnapShotID = null;
                }
                else
                {
                    StationEventPersonModel.ExtPartyStaffSnapShotID = nExtPartyStaffSnapShotID;
                }
                /*********************************/

                StationEventPersonModel.FlagObsolete = false;
                StationEventPersonModel.LastUpdUser = this.ODMUser.ID; //when update


                if (Session["CurrentTranferTime"] != null && Session["CurrentTranferTime"] != "")
                {
                    StationEventPersonModel.LastUpdTime = Convert.ToDateTime(Session["CurrentTranferTime"]);
                    Session["CurrentTranferTime"] = "";
                }
                else
                {
                    StationEventPersonModel.LastUpdTime = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime();
                }
                StationEventPersonModel.ActingasUser = this.ODMUser.ID;
            }
            //use StationEventPersonInfo
            //get StationEventAdmRegInfo
            StationEventAdmRegInfo StationEventAdmRegModel = new StationEventAdmRegInfo();
            if (this.SaveModel == 1)
            {
                StationEventAdmRegModel.StationEventAdmRegID = 0;
                StationEventAdmRegModel.StationEventID = 0;
            }
            else
            {
                StationEventAdmRegModel.StationEventAdmRegID = Convert.ToInt32(hdnStationEventAdmRegID.Value);
                StationEventAdmRegModel.StationEventID = Convert.ToInt32(hdnStationEventID.Value);
            }
            if (txtPersonNumber.Text != string.Empty)
            {
                StationEventAdmRegModel.EventNoOfWorkers = Convert.ToInt32(txtPersonNumber.Text);
            }
            else
            {
                StationEventAdmRegModel.EventNoOfWorkers = 0;
            }
            StationEventAdmRegModel.AdmRegCategoryID = Convert.ToInt32(ddlWorkCategory.SelectedValue); //it must have value,SPEC('Y')
            StationEventAdmRegModel.AdmRegSubCategoryID = Convert.ToInt32(ddlSubCategory.SelectedValue); //it must have value,,SPEC('Y')
            StationEventAdmRegModel.TNNo = txtTNNumber.Text;
            StationEventAdmRegModel.TransactionNo = txtTransactionNumber.Text;
            StationEventAdmRegModel.PossCertNo = txtPossessionCertNo.Text;
            StationEventAdmRegModel.JobNature = txtJobNature.Text;
            StationEventAdmRegModel.JobLocation = txtJobLocation.Text;
            StationEventAdmRegModel.JobProtection = txtJobProtection.Text;
            StationEventAdmRegModel.Remark = txtSupplement.Text;
            // to be finished...
            //StationEventAdmRegModel.ECSStatus1 = Convert.ToInt32(rblEngineControlSystemFirst.SelectedValue);
            if (rblEngineControlSystemFirst0.Checked == false && rblEngineControlSystemFirst1.Checked == false)
            {
                StationEventAdmRegModel.ECSStatus1 = 0;
            }
            else
            {
                StationEventAdmRegModel.ECSStatus1 = rblEngineControlSystemFirst0.Checked ? Convert.ToInt32(rblEngineControlSystemFirst0.Attributes["Value"]) : Convert.ToInt32(rblEngineControlSystemFirst1.Attributes["Value"]);
            }

            //StationEventAdmRegModel.ECSStatus2 = Convert.ToInt32(rblEngineControlSystemSecond.SelectedValue);
            if (rblEngineControlSystemSecond0.Checked == false && rblEngineControlSystemSecond1.Checked == false)
            {
                StationEventAdmRegModel.ECSStatus2 = 0;
            }
            else
            {
                StationEventAdmRegModel.ECSStatus2 = rblEngineControlSystemSecond0.Checked ? Convert.ToInt32(rblEngineControlSystemSecond0.Attributes["Value"]) : Convert.ToInt32(rblEngineControlSystemSecond1.Attributes["Value"]);
            }

            //StationEventAdmRegModel.ECSStatus3 = Convert.ToInt32(rblEngineControlSystemThird.SelectedValue);
            if (rblEngineControlSystemThird0.Checked == false && rblEngineControlSystemThird1.Checked == false)
            {
                StationEventAdmRegModel.ECSStatus3 = 0;
            }
            else
            {
                StationEventAdmRegModel.ECSStatus3 = rblEngineControlSystemThird0.Checked ? Convert.ToInt32(rblEngineControlSystemThird0.Attributes["Value"]) : Convert.ToInt32(rblEngineControlSystemThird1.Attributes["Value"]);
            }
            StationEventAdmRegModel.ECSStatus4 = 0;
            StationEventAdmRegModel.ECSStatus5 = 0;
            StationEventAdmRegModel.ECSStatus6 = 0;
            StationEventAdmRegModel.LastUpdUser = this.ODMUser.ID;
            StationEventAdmRegModel.LastUpdTime = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime();
            StationEventAdmRegModel.ActingasUser = this.ODMUser.ID;
            StationEventAdmRegModel.UserGroup = this.ODMUser.UserGroupID;
            //use StationEventAdmRegModel

            //PersonQualModel must have value(SPEC:Y)
            StationEventPersonQualInfo PersonQualModel = new StationEventPersonQualInfo();
            /* Comment by jack 20151008 for u50.1 reopen */
            if (this.hdnStaffType.Value == "3" || this.hdnStaffType.Value == "4")
            {
                PersonQualModel = null;
            }
            /********************************************/
            else if (this.SaveModel != 1 && hdnTransferResponsibilityKey.Value == string.Empty && hdnPersonHoldQualKye.Value == string.Empty)
            {
                PersonQualModel = null;
            }
            else
            {
                PersonQualModel.StationEventPersonQualID = 0;
                if (this.SaveModel == 1)
                {
                    PersonQualModel.StationEventPersonID = 0;
                }
                else
                {
                    if (hdnTransferResponsibilityKey.Value != string.Empty)
                    {
                        PersonQualModel.StationEventPersonID = 0;
                    }
                    else
                    {
                        PersonQualModel.StationEventPersonID = Convert.ToInt32(hdnStationEventPersonID.Value);
                    }
                }
                PersonQualModel.CQAQualificationID = 0;
                PersonQualModel.QualMasID = 0;
                PersonQualModel.QualCode = string.Empty;
                PersonQualModel.FlagObsolete = false;
                PersonQualModel.LastUpdUser = this.ODMUser.ID;
                PersonQualModel.LastUpdTime = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime();
                PersonQualModel.ActingasUser = this.ODMUser.ID;
                PersonQualModel.CQAID = this.txtStaffID.Text; //add by jack 20150703 for U50.2
            }

            //EventPersonTypeID(staff type)
            int nEventPersonTypeID = Convert.ToInt32(hdnStaffType.Value);

            //PersonQualModel
            int nPersonQualKey = 0;
            if (hdnPersonHoldQualKye.Value.Trim() != string.Empty)
            {
                nPersonQualKey = Convert.ToInt32(hdnPersonHoldQualKye.Value);
            }
            else if (hdnPersonHoldQualKye.Value == string.Empty)
            {
                PersonQualModel = null;
            }

            //get StationEventSignInfo object
            StationEventSignInfo StationEventSignArrive = new StationEventSignInfo();

            if (this.SaveModel == 1)
            {
                //update by benson 2015.07.27  U102 end
                //this.ucSignatureNew1.SaveTempFileToRealPath();//comment by gordon 20160224 - Save signature file to DB in varbinary field
                //ucSignatureArrivalBottom.SaveTempFileToRealPath();
                StationEventSignArrive.StationEventID = 0;
                StationEventSignArrive.StationEventPersonID = 0;
                StationEventSignArrive.EventSignType = 1;
                StationEventSignArrive.SignType = ucSignatureNew1.GetSignatureType();
                //forestall need check SignFileName, must have value
                StationEventSignArrive.SignFileName = ucSignatureNew1.GetSignatureFullFileName(1);
                StationEventSignArrive.Reason = "";
                //update by benson 2015.07.27  U102 end
                //add by Tim 20160226- Save signature file to DB in varbinary field
                 string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
                 if (Session[signatureName] != null)
                 {
                     StationEventSignArrive.SignFile = (byte[])Session[signatureName];
                 }
                 else
                 {
                     StationEventSignArrive.SignFile = null;
                 }
                
            }
            else
            {
                if (hdnTransferResponsibilityKey.Value != string.Empty)
                {
                    //update by benson 2015.07.27  U102 begin
                    //this.ucSignatureNew1.SaveTempFileToRealPath();//comment by gordon 20160224 - Save signature file to DB in varbinary field
                    //ucSignatureArrivalBottom.SaveTempFileToRealPath();
                    StationEventSignArrive.StationEventID = this.StationEventID;
                    StationEventSignArrive.StationEventPersonID = 0;
                    StationEventSignArrive.EventSignType = 1;
                    StationEventSignArrive.SignType = ucSignatureNew1.GetSignatureType();
                    //forestall need check SignFileName, must have value
                    StationEventSignArrive.SignFileName = ucSignatureNew1.GetSignatureFullFileName(1);
                    StationEventSignArrive.Reason = "";
                    //update by benson 2015.07.27  U102 end
                    //add by Tim 20160226- Save signature file to DB in varbinary field
                    string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
                    if (Session[signatureName] != null)
                    {
                        StationEventSignArrive.SignFile = (byte[])Session[signatureName];
                    }
                    else
                    {
                        StationEventSignArrive.SignFile = null;
                    }
                }
                else
                {
                    //update by benson 2015.07.27  U102 begin
                    if (hdnSignatureTypeArrive.Value != ucSignatureNew1.GetSignatureType().ToString() || hdnSignatureNameArrive.Value != ucSignatureNew1.GetSignatureFullFileName(1).ToString())
                    {
                        //this.ucSignatureNew1.SaveTempFileToRealPath();//comment by gordon 20160224 - Save signature file to DB in varbinary field
                        //ucSignatureArrivalBottom.SaveTempFileToRealPath();
                        StationEventSignArrive.StationEventID = this.StationEventID;
                        StationEventSignArrive.StationEventPersonID = Convert.ToInt32(hdnStationEventPersonID.Value);
                        StationEventSignArrive.EventSignType = 1;
                        StationEventSignArrive.SignType = ucSignatureNew1.GetSignatureType();
                        //forestall need check SignFileName, must have value
                        StationEventSignArrive.SignFileName = ucSignatureNew1.GetSignatureFullFileName(1);
                        StationEventSignArrive.Reason = "";
                        //add by Tim 20160226- Save signature file to DB in varbinary field
                        string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
                        if (Session[signatureName] != null)
                        {
                            StationEventSignArrive.SignFile = (byte[])Session[signatureName];
                        }
                        else
                        {
                            StationEventSignArrive.SignFile = null;

                        }
                    }
                    else
                    {
                        StationEventSignArrive = null;
                    }
                    //update by benson 2015.07.27  U102 end
                }
            }
            //update by benson 2015.07.27  U102 begin
            StationEventSignInfo StationEventSignDepart = new StationEventSignInfo();
            StationEventSignDepart = null;
            //if (this.SaveModel == 2)
            //{
            //    
            //    if (this.ucSignatureNew1.GetSignatureFullFileName(2).ToString() != string.Empty)
            //    {
            //        if (hdnTransferResponsibilityKey.Value != string.Empty)
            //        {
            //            //this.ucSignatureNew1.SaveTempFileToRealPath();
            //            StationEventSignDepart.StationEventID = this.StationEventID;
            //            StationEventSignDepart.StationEventPersonID = 0;
            //            StationEventSignDepart.EventSignType = 2;
            //            StationEventSignDepart.SignType = Convert.ToInt16(string.IsNullOrEmpty(hdnSignatureFromPopup.Value) ? "0" : hdnSignatureFromPopup.Value);//ucSignatureNew1.GetSignatureType();
            //            StationEventSignDepart.SignFileName = hdnSignatureFileNameFromPopup.Value;//ucSignatureNew1.GetSignatureFullFileName(2);
            //            StationEventSignDepart.Reason = "";
            //        }
            //        else
            //        {
            //            if (hdnSignatureTypeDepart.Value != ucSignatureNew1.GetSignatureType().ToString() || hdnSignatureNameDepart.Value != ucSignatureNew1.GetSignatureFullFileName(2).ToString())
            //            {
            //                //this.ucSignatureNew1.SaveTempFileToRealPath();
            //                StationEventSignDepart.StationEventID = this.StationEventID;
            //                StationEventSignDepart.StationEventPersonID = Convert.ToInt32(hdnStationEventPersonID.Value);
            //                StationEventSignDepart.EventSignType = 2;
            //                StationEventSignDepart.SignType = Convert.ToInt16(string.IsNullOrEmpty(hdnSignatureFromPopup.Value) ? "0" : hdnSignatureFromPopup.Value); //ucSignatureNew1.GetSignatureType();
            //                StationEventSignDepart.SignFileName = hdnSignatureFileNameFromPopup.Value;//ucSignatureNew1.GetSignatureFullFileName(2);
            //                StationEventSignDepart.Reason = "";
            //            }
            //            else
            //            {
            //                StationEventSignDepart = null;
            //            }
            //        }
            //    }
            //    else
            //    {
            //        StationEventSignDepart = null;
            //    }

            //}
            //else
            //{
            //    StationEventSignDepart = null;
            //}

            //update by benson 2015.07.27  U102 end
            StationEventAmendTimeInfo StationEventAmendTimeModel = new StationEventAmendTimeInfo();
            StationEventAmendTimeModel.StationEventAmendTimeID = 0;
            if (this.SaveModel == 1)
            {
                //alter this on 2008.12.12,by hzx
                StationEventAmendTimeModel.StationEventID = 0;
                if (lblArrivalTime.Text != hdnArrivalTimePrototype.Value)
                {
                    StationEventAmendTimeModel.InitialEventTime = this.ConvertToDateTime(hdnArrivalTimePrototype.Value.Trim());
                    StationEventAmendTimeModel.TimeType = 1;
                    //StationEventAmendTimeModel.SequenceNo = 1;
                    //update by benson 2015-10-24 u253 begin
                    StationEventAmendTimeModel.OriginalEventTime = this.ConvertToDateTime(this.lblArrivalTime.Text);
                    //update by benson 2015-10-24 u253 end
                    //update by benson 2015.07.29  U102 begin
                    StationEventAmendTimeModel.Reason = hdnChangeArrivalReason.Value;// txtChangeArrivalReason.Text;
                    //update by benson 2015.07.29  U102 end

                    //add by gordon 20160216 ISU51
                    //BLL.SOM.Log.Logger("AR->Save->SaveModel=1->OriginalEventTime Control[lblArrivalTime] Value:" + lblArrivalTime.Text, 4, ODMUser.ID, ODMUser.UserGroupName);
                   // BLL.SOM.Log.Logger("AR->Save->SaveModel=1->OriginalEventTime Model Value:" + this.FormatDateTime(StationEventAmendTimeModel.OriginalEventTime, true), 4, ODMUser.ID, ODMUser.UserGroupName);
                    //add end by gordon 20160216

                    if (!IsUserValidate())            //or (hdnFlagNeedValit.Value == "5")
                    {
                        StationEventAmendTimeModel.AmendUser = this.ODMUser.ID; //add by hzx, on20090109
                    }
                    else                             //or (hdnFlagNeedValit.Value == "4")
                    {
                        StationEventAmendTimeModel.AmendUser = int.Parse(Session[BLL.COM.Session.COM_Validation_UserID].ToString()); //add by hzx, on20090109
                    }
                }
                else
                {
                    StationEventAmendTimeModel = null;
                }
            }
            else
            {
                if (lblArrivalTime.Text != hdnArrivalTimePrototype.Value)
                {
                    StationEventAmendTimeModel.StationEventID = Convert.ToInt32(hdnStationEventID.Value);
                    StationEventAmendTimeModel.TimeType = 1;
                    StationEventAmendTimeModel.OriginalEventTime = this.ConvertToDateTime(lblArrivalTime.Text.Trim());
                    //update by benson 2015.07.29  U102 begin
                    StationEventAmendTimeModel.Reason = hdnChangeArrivalReason.Value;//txtChangeArrivalReason.Text;
                    //update by benson 2015.07.29  U102 end

                    //add by gordon 20160216 ISU51
                    //BLL.SOM.Log.Logger("AR->Save->SaveModel<>1->OriginalEventTime Control[lblArrivalTime] Value:" + lblArrivalTime.Text, 4, ODMUser.ID, ODMUser.UserGroupName);
                    //BLL.SOM.Log.Logger("AR->Save->SaveModel<>1->OriginalEventTime Model Value:" + this.FormatDateTime( StationEventAmendTimeModel.OriginalEventTime,true), 4, ODMUser.ID, ODMUser.UserGroupName);
                    //add end by gordon 20160216

                    if (!IsUserValidate())            //or (hdnFlagNeedValit.Value == "5")
                    {
                        StationEventAmendTimeModel.AmendUser = this.ODMUser.ID; //add by hzx, on20090109
                    }
                    else                             //or (hdnFlagNeedValit.Value == "4")
                    {
                        StationEventAmendTimeModel.AmendUser = int.Parse(Session[BLL.COM.Session.COM_Validation_UserID].ToString()); //add by hzx, on20090109
                    }
                }
                else
                {
                    StationEventAmendTimeModel = null;
                }
            }
            int assetLoanDataTmpID = -1;
            int.TryParse(this.hdnAssetLoanMainDataTmpID.Value.Trim(), out assetLoanDataTmpID);
            int assetLoanItemDataTmpID = -1;
            int.TryParse(this.hdnAssetLoanItemDataTmpID.Value.Trim(), out assetLoanItemDataTmpID);

            ////fire key
            int nFireSystemKey = -1;
            if (hdnFireSystemKey.Value != string.Empty)
            {
                nFireSystemKey = Convert.ToInt32(hdnFireSystemKey.Value);
            }
            int nStationEventPersonIDForFire = -1;
            if (StationEventPersonModel == null && hdnStationEventPersonID.Value != null && hdnStationEventPersonID.Value.Trim() != string.Empty)
            {
                nStationEventPersonIDForFire = Convert.ToInt32(hdnStationEventPersonID.Value);
            }

            int nStationEventID = 0;
            //add by benson 2015-09-07 begin
            if (this.IsChangeWrkHour == 1 && assetLoanDataTmpID <= 0 && assetLoanItemDataTmpID <= 0)
            {
                //ODMUser.StationID no longer use in store proc | Gordon 20151020
                DataTable dtAssetLoanEventIDList = MTRC.ODMS.DAL.SOM.Event.StationEventAssetLoanItemDa.GetAssetLoanItemByStationEventID(0, this.ODMUser.StationID, this.LangCode, this.StationEventID);

                StationEventInfo stationEventModel_AL = new StationEventInfo();
                StationEventAssetLoanInfo assetLoanModel = new StationEventAssetLoanInfo();
                StationEventAssetLoanItemInfo assetLoanItemModel = new StationEventAssetLoanItemInfo();
                Model.SOM.CodeSetup.ReminderMsgInfo reminderMsgInfo = new MTRC.ODMS.Model.SOM.CodeSetup.ReminderMsgInfo();
                if (dtAssetLoanEventIDList.Rows.Count > 0)
                {
                    stationEventModel_AL.ParentStationEventID = StationEventModel.StationEventID;
                    stationEventModel_AL.EventTime = StationEventModel.EventTime;
                    stationEventModel_AL.EstimatedWrkHour = StationEventModel.EstimatedWrkHour;
                    stationEventModel_AL.LastUpdUser = StationEventModel.LastUpdUser;
                    stationEventModel_AL.LastUpdTime = StationEventModel.LastUpdTime;
                    stationEventModel_AL.ActingasUser = StationEventModel.ActingasUser;
                    // add by dylan 20151009 for u228
                    stationEventModel_AL.FlagHandover = StationEventModel.FlagHandover;
                    //update by benson 2015-10-29 U269 begin
                    if (this.SaveModel == 1)
                    {
                        stationEventModel_AL.CreateUser = StationEventModel.CreateUser;
                    }
                    //update by benson 2015-10-29 U269 begin
                    DataRow dr = dtAssetLoanEventIDList.Rows[0];
                    stationEventModel_AL.StationEventID = Util.Int32FromDB(dr["StationEventID"]);
                    stationEventModel_AL.LocationID = Util.Int32FromDB(dr["LocationID"]);
                    stationEventModel_AL.EventNo = Util.StringFromDB(dr["EventNo"]);
                    stationEventModel_AL.EventStatusID = Util.Int32FromDB(dr["EventStatusID"]);
                    stationEventModel_AL.Remark = Util.StringFromDB(dr["Remark"]);
                    stationEventModel_AL.AmendReason = Util.StringFromDB(dr["AmendReason"]);
                    stationEventModel_AL.Description = Util.StringFromDB(dr["Description"]);

                    //assetLoanModel.StationEventAssetLoanID = Util.Int32FromDB(dr["StationEventAssetLoanID"]);
                    //assetLoanModel.StationEventID = Util.Int32FromDB(dr["StationEventID"]);

                    //assetLoanItemModel.StationEventAssetLoanItemID = Util.Int32FromDB(dr["StationEventAssetLoanItemID"]);
                    //assetLoanItemModel.StationEventAssetLoanID = assetLoanModel.StationEventAssetLoanID;

                    reminderMsgInfo.StationEventID = stationEventModel_AL.StationEventID;
                    reminderMsgInfo.FromTime = stationEventModel_AL.EventTime;
                    reminderMsgInfo.EventNo = stationEventModel_AL.EventNo;

                    // add by dylan 20151009 for u228
                    reminderMsgInfo.LocationID = stationEventModel_AL.LocationID;
                    // edit by dylan 20151012 for u237
                    //reminderMsgInfo.LastForMinutes = int.Parse(MTRC.ODMS.DAL.CommonData.GetNumVal("SOM_AR_NewsBar_LastForMinutes").ToString());
                    reminderMsgInfo.LastForMinutes = int.Parse(MTRC.ODMS.DAL.CommonData.GetNumVal("SOM_NewsBar_LastForMinutes").ToString());

                    string newsBarMsg1 = "";
                    string newsBarMsg2 = "";
                    string newsBarMsg3 = "";
                    string popupScreenMsg1 = "";
                    string popupScreenMsg2 = "";
                    string popupScreenMsg3 = "";

                    newsBarMsg1 = DAL.CommonData.GetStrVal("SOM_AssetLoan_NewsBarMsgTemplate1").Replace("[#EventNo]", stationEventModel_AL.EventNo);
                    newsBarMsg2 = DAL.CommonData.GetStrVal("SOM_AssetLoan_NewsBarMsgTemplate2").Replace("[#EventNo]", stationEventModel_AL.EventNo);
                    newsBarMsg3 = DAL.CommonData.GetStrVal("SOM_AssetLoan_NewsBarMsgTemplate3").Replace("[#EventNo]", stationEventModel_AL.EventNo);
                    popupScreenMsg1 = DAL.CommonData.GetStrVal("SOM_AssetLoan_PopupScreenMsgTemplate1").Replace("[#EventNo]", stationEventModel_AL.EventNo).Replace("[#EventTime]", APJ.Util.Utility.FormatDateTime(stationEventModel_AL.EventTime, true, true));
                    popupScreenMsg2 = DAL.CommonData.GetStrVal("SOM_AssetLoan_PopupScreenMsgTemplate2").Replace("[#EventNo]", stationEventModel_AL.EventNo).Replace("[#EventTime]", APJ.Util.Utility.FormatDateTime(stationEventModel_AL.EventTime, true, true));
                    popupScreenMsg3 = DAL.CommonData.GetStrVal("SOM_AssetLoan_PopupScreenMsgTemplate3").Replace("[#EventNo]", stationEventModel_AL.EventNo).Replace("[#EventTime]", APJ.Util.Utility.FormatDateTime(stationEventModel_AL.EventTime, true, true));
                    string linkStr = @"../../SOM/AssetLoan/AssetLoanEntry.aspx?StationEventID=[#StationEventID]";  //replace in db
                    /**********************************/
                    popupScreenMsg1 = popupScreenMsg1.Replace("[#Link]", linkStr);
                    popupScreenMsg2 = popupScreenMsg2.Replace("[#Link]", linkStr);
                    popupScreenMsg3 = popupScreenMsg3.Replace("[#Link]", linkStr);

                    reminderMsgInfo.NewsBarMsg1 = newsBarMsg1;
                    reminderMsgInfo.NewsBarMsg2 = newsBarMsg2;
                    reminderMsgInfo.NewsBarMsg3 = newsBarMsg3;
                    reminderMsgInfo.PopupScreenMsg1 = popupScreenMsg1;
                    reminderMsgInfo.PopupScreenMsg2 = popupScreenMsg2;
                    reminderMsgInfo.PopupScreenMsg3 = popupScreenMsg3;
                    reminderMsgInfo.FlagObsolete = false;

                    if (stationEventModel_AL.EstimatedWrkHour != 0)
                    {
                        reminderMsgInfo.ToTime = stationEventModel_AL.EventTime.AddMinutes(float.Parse(stationEventModel_AL.EstimatedWrkHour.ToString()) * 60);
                    }
                    else
                    {
                        reminderMsgInfo.ToTime = DateTime.MinValue;
                    }
                    reminderMsgInfo.LastUpdUser = stationEventModel_AL.LastUpdUser;
                    reminderMsgInfo.LastUpdTime = stationEventModel_AL.LastUpdTime;

                    //Change SP[usp_SOM_StationEvent_UpdateHandOverInfo] to Call in AR Submit SP - update by gordon 20151201
                    //nStationEventID = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.SaveNoTS(StationEventModel, StationEventPersonModel
                    //                                                         , StationEventAdmRegModel, PersonQualModel
                    //                                                         , StationEventSignArrive, StationEventSignDepart
                    //                                                         , StationEventAmendTimeModel, stationEventModel_AL
                    //                                                         , assetLoanModel, assetLoanItemModel, reminderMsgInfo, nPersonQualKey, this.SaveModel
                    //                                                         , assetLoanDataTmpID, assetLoanItemDataTmpID
                    //                                                         , this.ODMUser.ID, this.LangCode, nFireSystemKey, nEventPersonTypeID, nStationEventPersonIDForFire);
                    nStationEventID = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.SaveNoTS(StationEventModel, StationEventPersonModel
                                                                             , StationEventAdmRegModel, PersonQualModel
                                                                             , StationEventSignArrive, StationEventSignDepart
                                                                             , StationEventAmendTimeModel, stationEventModel_AL
                                                                             , assetLoanModel, assetLoanItemModel, reminderMsgInfo, nPersonQualKey, this.SaveModel
                                                                             , assetLoanDataTmpID, assetLoanItemDataTmpID
                                                                             , this.ODMUser.ID, this.ODMUser.UserGroupName, this.LangCode, nFireSystemKey, nEventPersonTypeID, nStationEventPersonIDForFire, this.StationEventID, txtHandoverCheckDetail.Text, chkHandoverCheck.Checked);
                    //this.ODMUser.UserGroupName
                    //Change - end by gordon 20151201
                }
                else
                {
                    //Change SP[usp_SOM_StationEvent_UpdateHandOverInfo] to Call in AR Submit SP - update by gordon 20151201
                    //nStationEventID = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.SaveNoTS(StationEventModel, StationEventPersonModel
                    //                                                          , StationEventAdmRegModel, PersonQualModel
                    //                                                          , StationEventSignArrive, StationEventSignDepart
                    //                                                          , StationEventAmendTimeModel, nPersonQualKey, this.SaveModel
                    //                                                          , assetLoanDataTmpID, assetLoanItemDataTmpID, this.ODMUser.ID, this.LangCode, nFireSystemKey, nEventPersonTypeID, nStationEventPersonIDForFire);
                    nStationEventID = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.SaveNoTS(StationEventModel, StationEventPersonModel
                                                                              , StationEventAdmRegModel, PersonQualModel
                                                                              , StationEventSignArrive, StationEventSignDepart
                                                                              , StationEventAmendTimeModel, nPersonQualKey, this.SaveModel
                                                                              , assetLoanDataTmpID, assetLoanItemDataTmpID, this.ODMUser.ID, this.ODMUser.UserGroupName, this.LangCode, nFireSystemKey, nEventPersonTypeID, nStationEventPersonIDForFire, this.StationEventID, txtHandoverCheckDetail.Text, chkHandoverCheck.Checked);
                    //Change - end by gordon 20151201
                }
            }
            //add by benson 2015-09-07 end
            else
            {
                //Change SP[usp_SOM_StationEvent_UpdateHandOverInfo] to Call in AR Submit SP - update by gordon 20151201
                /////save
                // edit by Kingkong Chan 20140729 for Code Merge (Issue 1488)
                //nStationEventID = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.SaveNoTS(StationEventModel, StationEventPersonModel
                //                                                            , StationEventAdmRegModel, PersonQualModel
                //                                                            , StationEventSignArrive, StationEventSignDepart
                //                                                            , StationEventAmendTimeModel, nPersonQualKey, this.SaveModel
                //                                                            , assetLoanDataTmpID, assetLoanItemDataTmpID, this.ODMUser.ID, this.LangCode, nFireSystemKey, nEventPersonTypeID, nStationEventPersonIDForFire);
                nStationEventID = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.SaveNoTS(StationEventModel, StationEventPersonModel
                                                                            , StationEventAdmRegModel, PersonQualModel
                                                                            , StationEventSignArrive, StationEventSignDepart
                                                                            , StationEventAmendTimeModel, nPersonQualKey, this.SaveModel
                                                                            , assetLoanDataTmpID, assetLoanItemDataTmpID, this.ODMUser.ID, this.ODMUser.UserGroupName, this.LangCode, nFireSystemKey, nEventPersonTypeID, nStationEventPersonIDForFire, this.StationEventID, txtHandoverCheckDetail.Text, chkHandoverCheck.Checked);
                //Change - end by gordon 20151201
            }
            /*
            int nStationEventID = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.Save(StationEventModel, StationEventPersonModel
                                                                         , StationEventAdmRegModel, PersonQualModel
                                                                         , StationEventSignArrive, StationEventSignDepart
                                                                         , StationEventAmendTimeModel, nPersonQualKey, this.SaveModel
                                                                         , assetLoanDataTmpID, assetLoanItemDataTmpID, this.ODMUser.ID, this.LangCode, nFireSystemKey, nEventPersonTypeID, nStationEventPersonIDForFire);
            */

            // add by dylan 20150928 for u196
            //ODMS.BLL.SOM.Event.StationEventAdmReg.UpdateStationEventHandOver(this.StationEventID, txtHandoverCheckDetail.Text, chkHandoverCheck.Checked, this.ODMUser.ID);//remove by gordon 20151201 change to call in AR Submit SP

            this.IsChangeWrkHour = 0;
            this.hdnAssetLoanMainDataTmpID.Value = "";
            this.hdnAssetLoanItemDataTmpID.Value = "";
            Session[BLL.COM.Session.SOM_ResponsibilityTransfer + this.StationEventID.ToString()] = null;
            hdnTransferResponsibilityKey.Value = "";
            hdnPersonHoldQualKye.Value = "";
            //this.StationEventID = nStationEventID;//comment by gordon 20160218 ISU45
            this.SaveModel = 2;
            hdnStationEventLastUpdataTime.Value = StationEventModel.LastUpdTime.ToString();
           // ucSignatureNew1.clearSignSession();//add by Tim 20160224 - Save signature file to DB in varbinary field
            return nStationEventID;
        }

        /// <summary>
        /// Validation page data
        /// </summary>
        /// <returns></returns>
        private bool ValidationBeforeSaveOperation(bool IsSaveButon)
        {
            string staffID = this.txtStaffID.Text.Trim();
            if (staffID == string.Empty)
            {
                if (IsSaveButon)
                {
                    this.Alert(this.GetMessage("SOM_StaffIDShouldNotBeEmpty"));
                }
                else
                {
                    PAlert(this.GetMessage("SOM_StaffIDShouldNotBeEmpty"));
                }
                return false;
            }
            string staffName = this.txtStaffName.Text.Trim();
            if (this.txtStaffName.Enabled && staffName == string.Empty)
            {
                if (IsSaveButon)
                {
                    this.Alert(this.GetMessage("SOM_StaffNameShouldNotBeEmpty"));
                }
                else
                {
                    PAlert(this.GetMessage("SOM_StaffNameShouldNotBeEmpty"));
                }
                return false;
            }

            if (this.oldCompany.Style["display"] == "block")
            {
                string departmentCompany = this.txtDepartmentCompany.Text.Trim();
                if (this.txtDepartmentCompany.Enabled && departmentCompany == string.Empty)
                {
                    if (IsSaveButon)
                    {
                        this.Alert(this.GetMessage("SOM_DeptCompShouldNotBeEmpty"));
                    }
                    else
                    {
                        PAlert(this.GetMessage("SOM_DeptCompShouldNotBeEmpty"));
                    }
                    return false;
                }
            }
            else
            {
                string oUCompany = this.txtSelectedOU.Value.Trim();
                if (string.IsNullOrEmpty(oUCompany) || oUCompany == "")
                {
                    if (IsSaveButon)
                    {
                        this.Alert(this.GetMessage("SOM_DeptCompShouldNotBeEmpty"));
                    }
                    else
                    {
                        PAlert(this.GetMessage("SOM_DeptCompShouldNotBeEmpty"));
                    }
                    return false;
                }
            }

            string strContactNo = this.txtContactNo.Text.Trim();
            if (this.txtContactNo.Enabled && strContactNo == string.Empty)
            {
                if (IsSaveButon)
                {
                    this.Alert(this.GetMessage("SOM_ContactTelShouldNotBeEmpty"));
                }
                else
                {
                    PAlert(this.GetMessage("SOM_ContactTelShouldNotBeEmpty"));
                }
                return false;
            }

            //update by gordon 20151019 U247
            //if (!DAL.SOM.Event.StationEventDa.IsLegalStation(this.ODMUser.StationID))
            if (!DAL.SOM.Event.StationEventDa.IsLegalStation(this.ODMUser.LocationID))
            {
                if (IsSaveButon)
                {
                    this.Alert(this.GetMessage("SOM_LegalStationCheck"));
                }
                else
                {
                    PAlert(this.GetMessage("SOM_LegalStationCheck"));
                }
                return false;
            }
            //Modify by elvis on 20180131 for SER-2018056 （default not load  SignaturePaint.）-->
            if (CommonData.GetCharVal("SOM_Sign_Must").Trim() == "Y")
            {
                //update by benson 2015.07.27  U102 begin
                if (this.ucSignatureNew1.GetSignatureFullFileName(1) == string.Empty)
                {
                    if (IsSaveButon)
                    {
                        this.Alert(this.GetMessage("SOM_EventSignCheck"));
                    }
                    else
                    {
                        PAlert(this.GetMessage("SOM_EventSignCheck"));
                    }
                    return false;
                }
                if (this.ucSignatureNew1.IsNeedSignAgain)
                {
                    if (IsSaveButon)
                    {
                        this.Alert(this.GetMessage("SOM_NeedSignutrueAgainMsg"));
                    }
                    else
                    {
                        PAlert(this.GetMessage("SOM_NeedSignutrueAgainMsg"));
                    }
                    return false;
                }
                if (this.ucSignatureNew1.GetSignatureFullFileName(2).ToString() != string.Empty)
                {
                    if (this.ucSignatureNew1.IsNeedSignAgain)
                    {
                        if (IsSaveButon)
                        {
                            this.Alert(this.GetMessage("SOM_NeedSignutrueAgainMsg"));
                        }
                        else
                        {
                            PAlert(this.GetMessage("SOM_NeedSignutrueAgainMsg"));
                        }
                        return false;
                    }
                }
                //update by benson 2015.07.27  U102 end
            }
            //<--Modify by elvis on 20180131 for SER-2018056 （default not load  SignaturePaint.）
            if (ddlWorkCategory.SelectedIndex == 0)
            {
                if (IsSaveButon)
                {
                    this.Alert(this.GetMessage("SOM_MustCheckWorkCategory"));
                }
                else
                {
                    PAlert(this.GetMessage("SOM_MustCheckWorkCategory"));
                }
                return false;
            }
            if (ddlSubCategory.SelectedIndex == 0)
            {
                if (IsSaveButon)
                {
                    this.Alert(this.GetMessage("SOM_MustCheckSubWorkCategory"));
                }
                else
                {
                    PAlert(this.GetMessage("SOM_MustCheckSubWorkCategory"));
                }
                return false;
            }

            //add by gordon 20150723 U132.3
            object flagProtect = ViewState["FlagProtect"];
            if (flagProtect != null)
            {
                string strProtect = flagProtect.ToString();
                if (strProtect == "1" && emMandatory.Visible)
                {
                    if (string.IsNullOrEmpty(txtTransactionNumber.Text.Trim()))
                    {
                        if (IsSaveButon)
                        {
                            Alert(GetMessage("SOM_TransactionNoShouldNotBeEmpty"));
                        }
                        else
                        {
                            PAlert(GetMessage("SOM_TransactionNoShouldNotBeEmpty"));
                        }
                        return false;
                    }
                }
            }

            //add by gordon 20160202 - ISU35
            string assetItemCode = "";
            int availableQty = 0;
            int assetItemID = -1;
            DataTable assetLoanItemDT = GetAssetLoanItemDataTable();
            if (assetLoanItemDT != null)
            {
                StringBuilder sbAssetItemAlertMsg = new StringBuilder();
                bool isNeedReturnFalse = false;
                string newLineIndicator = @"\n";

                foreach (DataRow dr in assetLoanItemDT.Select("", "LoanTime DESC"))
                {
                    if (Util.Int32FromDB(dr["StationEventAssetLoanID"]) > 0 && Util.Int32FromDB(dr["StationEventID"]) > 0)
                    {
                        continue;
                    }

                    if (dr["ReturnTime"] != System.DBNull.Value)
                    {
                        continue;
                    }

                    assetItemCode = Util.StringFromDB(dr["CDAI_AssetitemCode"]);
                    assetItemID = Util.Int32FromDB(dr["AssetItemID"]);
                    availableQty = this.CalculateAvailableQty(assetItemID, Util.Int32FromDB(dr["StationEventAssetLoanItemID"]));
                    if (availableQty < 1)
                    {
                        sbAssetItemAlertMsg.Append(this.GetMessage("SOM_LatestLoanItemMsg") + assetItemCode + "--" + this.GetMessage("SOM_AvailableQtyNegativeCanNotAdd"));
                        sbAssetItemAlertMsg.Append(newLineIndicator);
                        isNeedReturnFalse = true;
                    }
                    if (availableQty < Util.Int32FromDB(dr["NumOfLoanItem"]))
                    {
                        sbAssetItemAlertMsg.Append(this.GetMessage("SOM_LatestLoanItemMsg") + assetItemCode + "--" + this.GetMessage("SOM_LoanNumNeedLessOrEqualThanAvailableNum"));
                        sbAssetItemAlertMsg.Append(newLineIndicator);
                        isNeedReturnFalse = true;
                    }
                }
                if (isNeedReturnFalse)
                {
                    sbAssetItemAlertMsg.Append(newLineIndicator);
                    sbAssetItemAlertMsg.Append(this.GetMessage("SaveUnsuccessfully"));
                    if (IsSaveButon)
                    {
                        this.Alert(sbAssetItemAlertMsg.ToString());
                    }
                    else
                    {
                        this.PAlert(sbAssetItemAlertMsg.ToString());
                    }
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// GetAssetLoanItemDataTable
        /// ISU35 - add by gordon 20160202
        /// </summary>
        /// <returns></returns>
        private DataTable GetAssetLoanItemDataTable()
        {
            int tmpId = 0;
            int.TryParse(hdnAssetLoanItemDataTmpID.Value, out tmpId);
            if (tmpId != 0)
            {
                return BLL.SOM.TempData.GetCacheData(tmpId).Tables[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// CalculateAvailableQty
        /// ISU35 - add by gordon 20160202
        /// </summary>
        /// <param name="assetItemID"></param>
        /// <param name="noNeedIncludeStationEventAssetLoanItemID"></param>
        /// <returns></returns>
        private int CalculateAvailableQty(int assetItemID, int noNeedIncludeStationEventAssetLoanItemID)
        {
            int availableQty = DAL.SOM.CodeSetup.CDAssetItem.GetAvailableQtyByID(assetItemID);

            DataTable dt = GetAssetLoanItemDataTable();
            if (dt != null)
            {
                string selectStr = "AssetItemID=" + assetItemID.ToString();
                if (noNeedIncludeStationEventAssetLoanItemID > 0)
                {
                    selectStr = selectStr + " and StationEventAssetLoanItemID<>" + noNeedIncludeStationEventAssetLoanItemID.ToString();
                }

                int totalCountOfLoan = 0;
                int totalCountOfReturn = 0;
                foreach (DataRow dr in dt.Select(selectStr))
                {
                    if (Util.StringFromDB(dr["LoanStationEventSignID"]) == string.Empty)
                    {
                        totalCountOfLoan += Util.Int32FromDB(dr["NumOfLoanItem"]);
                        totalCountOfReturn += Util.Int32FromDB(dr["NumOfReturnItem"]);
                    }
                    else
                    {
                        DataTable dt_EventAssetLoanItem = DAL.SOM.CodeSetup.CDAssetItem.GetByStationEventAssetLoanItemID(Util.Int32FromDB(dr["StationEventAssetLoanItemID"]));
                        if (Util.Int32FromDB(dr["StationEventAssetLoanItemID"]) == Util.Int32FromDB(dt_EventAssetLoanItem.Rows[0]["StationEventAssetLoanItemID"]) && Util.DateTimeFromDB(dr["ReturnTime"]) != Util.DateTimeFromDB(dt_EventAssetLoanItem.Rows[0]["ReturnTime"]))
                        {
                            totalCountOfReturn += Util.Int32FromDB(dr["NumOfReturnItem"]);
                        }
                    }
                }
                availableQty = availableQty - totalCountOfLoan + totalCountOfReturn;
            }
            return availableQty;
        }

        /// <summary>
        /// Depart Station Validation
        /// </summary>
        /// <returns></returns>
        private bool ValidationDepart()
        {
            if (ViewState["FlagReqSign"].ToString() == "1" || ViewState["SubFlagReqSign"].ToString() == "1")
            {
                //update by benson 2015.07.27  U102 begin
                //if (ucSignatureDeparture.GetSignatureFullFileName(2).ToString() == string.Empty)
                //{
                //    this.PAlert(this.GetMessage("SOM_DepartStationMustSign"));
                //    return false;
                //}
                if (this.ucSignatureNew1.GetSignatureFullFileName(2).ToString() == string.Empty)
                {
                    this.PAlert(this.GetMessage("SOM_DepartStationMustSign"));
                    return false;
                }
                //update by benson 2015.07.27  U102 begin
            }
            return true;
        }

        /// <summary>
        /// check StationEventID exist with same TNNo 
        /// </summary>
        /// <returns>false:no have, don't need message ;   true:have,need message</returns>
        private bool IsTNProtected()
        {
            //edit by hjh 20120519 for DataReader not close
            bool returnval = false;
            // Commented by Kingkong Chan 20150803
            //if (ViewState["FlagProtect"].ToString() == "1" || ViewState["SubFlagProtect"].ToString() == "1")
            //{
            // Commented by Kingkong Chan 20150803
            if (ViewState["FlagProtect"].ToString() == "1" && ViewState["SubFlagProtect"].ToString() == "0")
            {
                // Commented by Kingkong Chan 20150803
                //string strTNNo = txtTNNumber.Text;
                //using (SqlDataReader drGetProtectEventID = ODMS.BLL.SOM.Event.StationEventAdmReg.GetProtectEventIDByStationEvent(strTNNo, this.StationEventID))
                // Commented by Kingkong Chan 20150803

                string strTransactionNo = txtTransactionNumber.Text;
                using (SqlDataReader drGetProtectEventID = ODMS.BLL.SOM.Event.StationEventAdmReg.GetProtectEventIDByStationEvent(strTransactionNo, this.StationEventID))
                {
                    if (drGetProtectEventID.HasRows)
                    {
                        drGetProtectEventID.Read();
                        drGetProtectEventID.Close();
                        drGetProtectEventID.Dispose();
                        returnval = true;
                    }
                }
            }
            return returnval;
        }

        /// <summary>
        /// Check save is or not need user validate
        /// </summary>
        /// <returns></returns>
        private bool IsUserValidate()
        {
            //if (DAL.Security.User.CanFunctionItemAccess("M14_F2", this.ODMUser.UserProfileID, "M14"))
            if (DAL.Security.User.CanFunctionItemAccess("M140102_F2", this.ODMUser.UserProfileID, this.MenuID)) //huangyao 20081022 fixed issue 0453
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Domain User Validate
        /// </summary>
        /// <param name="RequirePasswordStaffInfoID"></param>
        /// <returns></returns>
        private bool UserValidate(out string RequirePasswordUserID, out int RequirePasswordStaffInfoID)
        {
            //edit by hjh 20120519 for DataReader not close
            bool returnval = false;
            RequirePasswordStaffInfoID = 0;
            RequirePasswordUserID = string.Empty;
            if (hdnFlagNeedValit.Value == "4" || hdnFlagNeedValit.Value == "3")
            {
                int ValidationUserID = int.Parse(Session[BLL.COM.Session.COM_Validation_UserID].ToString());
                if (ValidationUserID == -2)
                {
                    this.PAlert(this.GetMessage("LPM_Valiate_NotValidate"));
                    returnval = false;
                }
                else if (ValidationUserID == -1)
                {
                    this.PAlert(this.GetMessage("LPM_Validate_ValidateFailed"));
                    returnval = false;
                }
                else if (ValidationUserID == 0)
                {
                    this.PAlert(this.GetMessage("LPM_Validate_NotSysUser"));
                    returnval = false;
                }
                else if (ValidationUserID > 0)
                {
                    DataTable dt = MTRC.ODMS.DAL.Security.User.GetUserList(ValidationUserID);
                    RequirePasswordUserID = MTRC.ODMS.DAL.COM.Util.StringFromDB(dt.Rows[0]["UserID"]);
                    if (DAL.CommonData.GetCharVal("SOM_CheckStaffInfo").ToString().Trim().ToUpper() == "Y")
                    {
                        using (SqlDataReader drStaffInfoID = BLL.SOM.Event.StationEventAdmReg.GetStaffInfoIDByIDToValidate(ValidationUserID))
                        {
                            if (drStaffInfoID.HasRows)
                            {
                                drStaffInfoID.Read();
                                RequirePasswordStaffInfoID = int.Parse(drStaffInfoID["StaffInfoID"].ToString());
                                returnval = true;
                            }
                            else
                            {
                                PAlert(GetMessage("SOM_NotValidateMTRStaff"));
                                returnval = false;
                            }
                        }
                    }
                    else
                    {
                        returnval = true;
                    }
                }
            }
            else if (hdnFlagNeedValit.Value == "5" || hdnFlagNeedValit.Value == "1")
            {
                returnval = true;
            }
            return returnval;
        }

        /// <summary>
        /// doing something after save
        /// </summary>
        /// update by gordon 20160215 ISU45
        //private void SettingAfterSave(bool IsSaveButon)
        private void SettingAfterSave(bool IsSaveButon,int StationEventID)
        {
            string addScript = string.Empty;
            if (this.hdnFlagNeedValit.Value == "1")
            {
                this.hdnFlagNeedValit.Value = "";
            }
            addScript = "location.href='" + Request.RawUrl + "'";
            if (Request.RawUrl.IndexOf("StationEventID=") > 0)
            {
                addScript = addScript.Replace("StationEventID=" + Request.QueryString["StationEventID"].ToString(), "StationEventID=" + this.StationEventID);
                if (Request.QueryString["Destroy"] != null)
                {
                    if (Request.RawUrl.IndexOf("Destroy=") > 0)
                    {
                        //comment by jack 20151020 for u239.2
                        //addScript = addScript.Replace("@Destroy=" + Request.QueryString["Destroy"].ToString(), "");
                        addScript = addScript.Remove(addScript.Length - 1) + "&IsSaveButton=TRUE" + "'";
                        addScript = addScript.Replace("@Destroy=" + Request.QueryString["Destroy"].ToString(), "");
                    }
                    else
                    {
                        addScript = addScript.Replace("Destroy=" + Request.QueryString["Destroy"].ToString(), "");
                    }
                }
            }
            else
            {
                if (Request.QueryString["Action"] != null)
                {
                    // update by gordon 20160215 ISU45
                    //addScript = "location.href='" + Request.RawUrl + "&StationEventID=" + this.StationEventID + "'";
                    addScript = "location.href='" + Request.RawUrl + "&StationEventID=" + StationEventID + "'";
                }
                else
                {
                    // update by gordon 20160215 ISU45
                    //addScript = "location.href='" + Request.RawUrl + "?StationEventID=" + this.StationEventID + "'";
                    addScript = "location.href='" + Request.RawUrl + "?StationEventID=" + StationEventID + "'";
                }
            }
            if (IsSaveButon)
            {
                this.Alert(this.GetMessage("SaveSuccessfully"), 10, addScript);
            }
            else
            {
                PAlert(this.GetMessage("SaveSuccessfully"), 10, addScript);
            }
            this.IsServerChanged = false;
        }

        private void CopyAsNewSetting()
        {
            ViewState["FlagReqSign"] = "0";
            ViewState["SubFlagReqSign"] = "0";

            ViewState["FlagProtect"] = "0";
            ViewState["SubFlagProtect"] = "0";

            this.SaveModel = 1;
            this.ReadOnly = false;
            //add new
            //this.StationEventID = -1;//comment by gordon 20160218 ISU45
            lblRegistryNumber.Text = string.Empty;
            lblTransferredFlag.Visible = false;
            lblNewlyCreatedFlag.Visible = true;
            hdnStationEventID.Value = "";
            hdnStatus.Value = "";
            hdnHighLight.Value = "";
            imgStatus.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
            imgHighLight.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
            //update by benson 2015-10-24 u253 begin
            lblArrivalTime.Text = this.FormatDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime(), true);

            //add by gordon 20160216 ISU51
            //BLL.SOM.Log.Logger("AR->CopyAsNewSetting->lblArrivalTime:" + lblArrivalTime.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

            //this.dtbArrivalTime.SetDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime());
            //this.dtbArrivalTime.Visible = true;
            //this.lblArrivalTime.Visible = false;
            //update by benson 2015-10-24 end
            string[] split = lblArrivalTime.Text.Split(new char[] { ' ' });
            hdnArrivalDate.Value = split[0];
            hdnArrivalTime.Value = split[1];
            hdnArrivalTimePrototype.Value = this.FormatDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime(), true);
            btnOpenChangeEventTime.Attributes.Add("style", "background-color: inherit;");
            hdnAmendTimeVal.Value = "";
            //update by benson 2015.07.27  U102 begin
            //hdnChangeArrivalReason.Value = "";
            //txtChangeArrivalReason.Text = string.Empty;
            //update by benson 2015.07.27  U102 end
            hdnStationEventPersonID.Value = "";
            hdnTransferResponsibilityKey.Value = "";
            hdnTransferChange.Value = "";

            //Add By Gordon 2015/06/15 
            //Ref To Req 18.4 Do not Copy To New Record
            chkHandoverCheck.Checked = false;
            txtHandoverCheckDetail.Enabled = false;
            txtStaffID.Text = txtStaffName.Text = txtContactNo.Text = txtHandoverCheckDetail.Text = string.Empty;
            //To Be Upd OU/Company,Qualification 
            txtDepartmentCompany.Text = string.Empty;
            ddlDepartmentCompany.Items.Clear();
            ddlQualification.Items.Clear();
            txtQualification.Text = string.Empty;

            imgSearchStaff.Visible = true;
            if (hdnStaffType.Value == "4")
            {
                txtStaffID.Enabled = true;
                txtStaffName.Enabled = true;
                txtDepartmentCompany.Enabled = true;
            }
            btnTransferResponsibility.Enabled = false;

            txtContactNo.Enabled = true;

            txtOrganizationUnit.Enabled = false;
            hdnOrganizationUnit.Value = "";
            txtOrganizationUnit.Text = string.Empty;

            txtPersonNumber.Enabled = true;
            txtPersonNumber.Text = CommonData.GetNumVal("SOM_AR_NumberOfWorkers").ToString();

            hdnStationEventPersonQualID.Value = "";
            hdnPersonHoldQualKye.Value = "";
            btnMoreQualification.Enabled = true;
            txtQualification.Text = string.Empty;

            //ucSignatureArrivalBottom.InitUCSignatureValue(1, 1, "");
            //ucSignatureArrivalBottom.SetEnable(true, 1);

            hdnStationEventSignID.Value = "";
            hdnSignatureTypeArrive.Value = "";
            hdnSignatureNameArrive.Value = "";
            hdnSignatureFileNameFromPopup.Value = "";
            //add by benson 2015-09-15 U205 begin
            Session[MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival] = null;
            imgSignature.Visible = false;
            lblDepartureTime.Text = "";
            //add by benson 2015-09-15 U205 end

            //update by benson 2015.07.27 u102 begin
            this.ucSignatureNew1.InitUCSignatureValue(1, 2, "");
            this.ucSignatureNew1.SetEnable(true, 1);
            //update by benson 2015.07.27 u102 end

            txtRemark.Enabled = true;
            txtRemark.Text = string.Empty;

            hdnDepartDate.Value = "";
            hdnDepartTime.Value = "";
            hdnChangeDepartReason.Value = "";
            hdnStationEventCompleteSignID.Value = "";
            hdnSignatureTypeDepart.Value = "";
            hdnSignatureNameDepart.Value = "";
            //update by benson 2015.07.27 u102 begin
            //ucSignatureDeparture.InitUCSignatureValue(2, 1, "");
            //ucSignatureDeparture.SetEnable(false, 2, false);
            //ucSignatureDepartureBottom.InitUCSignatureValue(2, 1, "");
            //ucSignatureDepartureBottom.SetEnable(false, 2, false);
            //imgDepartureAmendBottom.Enabled = false;
            //imgCompletionTasksDeparture.Enabled = false;
            //imgCompletionTasksDepartureBottom.Enabled = false;
            //imgDepartureBottom.Enabled = false;

            //imgDepartureAmend.Enabled = false;

            imgDeparture.Enabled = false;
            btnDeparture.Enabled = false;
            btnDepartureAmend.Enabled = false;
            btnDepartureAmend.Visible = false;
            //update by benson 2015.07.27 u102 end
            hdnStationEventAdmRegID.Value = "";
            ddlWorkCategory.Enabled = true;
            ddlSubCategory.Enabled = true;

            txtTNNumber.Enabled = true;
            txtTNNumber.Text = string.Empty;
            txtTransactionNumber.Enabled = true;
            txtTransactionNumber.Text = string.Empty;
            txtPossessionCertNo.Enabled = true;
            txtPossessionCertNo.Text = string.Empty;

            txtJobNature.Enabled = true;
            txtJobLocation.Enabled = true;
            txtJobProtection.Enabled = true;

            txtEstimatedCompletionTime.Enabled = true;
            txtEstimatedCompletionTime.Text = string.Empty;
            lblShouldCompletionTime.Text = string.Empty;
            txtSupplement.Enabled = true;



            chkHandoverCheck.Enabled = true;
            if (chkHandoverCheck.Checked == true)
            {
                txtHandoverCheckDetail.Enabled = true;
            }
            else
            {
                txtHandoverCheckDetail.Text = string.Empty;
            }

            rblEngineControlSystemFirst0.Enabled = true;
            rblEngineControlSystemFirst1.Enabled = true;

            rblEngineControlSystemSecond0.Enabled = true;
            rblEngineControlSystemSecond1.Enabled = true;

            rblEngineControlSystemThird0.Enabled = true;
            rblEngineControlSystemThird1.Enabled = true;

            btnSave.Enabled = true;
            //btnSaveBottom.Enabled = true;
            btnSaveTop.Enabled = true;

            lblALEventNumber.Text = string.Empty;
            imgALStatus.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
            imgALHighLight.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
            hdnAssetLoanMainDataTmpID.Value = "";
            hdnAssetLoanItemDataTmpID.Value = "";
            hdnAssetLoanItemTmpIDChangeFlag.Value = "";

            hdnFireSystemKey.Value = "";

            hdnFlagDepature.Value = "";
            hdnFlagBookOff.Value = "";
            hdnFlagNeedValit.Value = "";
            hdnRequirePasswordStaffInfoID.Value = "";

            btnFireAdd.Enabled = true;
            grdFireSystem.Enabled = true;
            btnAddNewAssetLoan.Enabled = true;
            grdAssetLoan.Enabled = true;

            SettingAssetLoanGridByData();
            SettingFireGridByDataBind();

            //Add By Gordon 2015/06/15
            //Ref To Req18.4
            txtStaffID_TextChanged(null, null);
            txtStaffID.Enabled = true;

            // add by dylan 20150821 for u81.1
            this.btnHandoverCheck.Enabled = false;

        }

        public void ExportSetting(bool callByBookOffHandling)
        {
            System.Collections.Generic.List<string> res = AREntryExport();
            if (callByBookOffHandling)
            {
                this.hdnfilePath.Value = res[0];
                this.hdnfileName.Value = res[1];
                this.hdncontent.Value = Server.HtmlEncode(res[2]); //tfs 1937
                this.hdndayBeforeParam.Value = res[3];
            }
            else
            {
                AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "ExportHtmlToLocal", "<script language='javascript' type='text/javascript'>ExportHtmlToLocal('" + res[0] + "', '" + res[1] + "', '" + res[2] + "', '" + res[3] + "');</script>", false); //by zengshunbo 2009-04-30 issue1169
            }
        }

        //modified by haungyao 20090226:  by huangyao 20090226, fixed the issue 1035
        private void ExportHtmlToServer(DataTable dtExportTable, string fileName)
        {
            TextWriter tw = new StreamWriter(fileName, false, Encoding.Unicode);
            //tw.WriteLine
            string strDateTime = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime().ToString();
            StringBuilder sbStream = new StringBuilder();
            tw.WriteLine("<HTML>");
            tw.WriteLine("<HEAD><TITLE>" + this.GetLabel("COM_SystemName_SOM") + "</TITLE></HEAD>");
            tw.WriteLine("<BODY>");
            tw.WriteLine("<Table border=" + '"' + "1" + '"' + " " + "cellpadding=" + '"' + "0" + '"' + " " + "cellspacing=" + '"' + "0" + '"' + " " + "WIDTH=" + '"' + "726" + '"' + " " + "style=" + '"' + "border-collapse:collapse;" + '"' + ">");
            tw.WriteLine("<TR><TD WIDTH=" + '"' + "110" + '"' + "></TD><TD WIDTH=" + '"' + "60" + '"' + "></TD><TD WIDTH=" + '"' + "110" + '"' + "></TD><TD WIDTH=" + '"' + "110" + '"' + "></TD><TD WIDTH=" + '"' + "121" + '"' + "></TD><TD WIDTH=" + '"' + "55" + '"' + "></TD><TD WIDTH=" + '"' + "33" + '"' + "></TD><TD WIDTH=" + '"' + "99" + '"' + "></TD><TD WIDTH=" + '"' + "88" + '"' + "></TD></TR>");
            tw.WriteLine("<TR><TH ALIGN=" + '"' + "left" + '"' + ">" + this.GetLabel("SOM_StationEventCreateTime") + "</TH><TH ALIGN=" + '"' + "left" + '"' + ">" + this.GetLabel("SOM_RecordsIndex") + "</TH><TH ALIGN=" + '"' + "left" + '"' + ">" + dtExportTable.Columns[0].ColumnName + "</TH><TH ALIGN=" + '"' + "left" + '"' + ">" + dtExportTable.Columns[1].ColumnName + "</TH><TH ALIGN=" + '"' + "left" + '"' + ">" + dtExportTable.Columns[2].ColumnName + "</TH><TH ALIGN=" + '"' + "left" + '"' + ">" + dtExportTable.Columns[3].ColumnName + "</TH><TH ALIGN=" + '"' + "left" + '"' + ">" + dtExportTable.Columns[4].ColumnName + "</TH><TH ALIGN=" + '"' + "left" + '"' + ">" + dtExportTable.Columns[5].ColumnName + "</TH><TH ALIGN=" + '"' + "left" + '"' + ">" + dtExportTable.Columns[6].ColumnName + "</TH></TR>");

            for (int i = 0; i < dtExportTable.Rows.Count; i++)
            {
                if (i == dtExportTable.Rows.Count - 1)
                {
                    tw.WriteLine("<TR><TH></TH><TH></TH><TH></TH><TH></TH><TH>" + this.Server.HtmlEncode(dtExportTable.Rows[i][2].ToString()) + "</TH><TH></TH><TH>" + this.Server.HtmlEncode(dtExportTable.Rows[i][4].ToString()) + "</TH><TH></TH><TH></TH></TR>");
                }
                else
                {
                    if (i == 0)
                    {
                        tw.WriteLine("<tr valign=top>");
                        tw.WriteLine("<td rowspan=" + '"' + (dtExportTable.Rows.Count - 1) + '"' + ">" + strDateTime + "</td>");
                    }
                    tw.WriteLine("<td>");
                    tw.WriteLine(i + 1);
                    tw.WriteLine("</td>");
                    foreach (DataColumn dc in dtExportTable.Columns)
                    {
                        tw.WriteLine("<td>");
                        tw.WriteLine(SetSpecialToNormal(this.Server.HtmlEncode(dtExportTable.Rows[i][dc].ToString())));
                        tw.WriteLine("</td>");
                    }
                    tw.WriteLine("</tr>");
                }
            }
            tw.WriteLine("</table>");
            tw.WriteLine("</BODY>");
            tw.WriteLine("</HTML>");
            tw.Close();
        }

        private void SaveQualificationToTempData()
        {
            DataTable dtTemp = new DataTable();
            dtTemp.Columns.Add("CDQualCode");
            dtTemp.Columns.Add("QualCode");
            dtTemp.Columns.Add("QualDesc");
            dtTemp.Columns.Add("CQAID");

            if (!string.IsNullOrEmpty(ddlQualification.SelectedValue))
            {
                if (ddlQualification.SelectedValue.Contains(';'))
                {//many
                    string[] arrQualCode = ddlQualification.SelectedValue.Trim().Split(';');
                    foreach (var itemQualCode in arrQualCode)
                    {
                        DataRow dr = dtTemp.NewRow();
                        if (itemQualCode.Trim().Contains(' '))
                        {
                            dr["QualCode"] = itemQualCode.Trim().Split(' ')[0];
                            dr["QualDesc"] = itemQualCode.Trim().Split(' ')[1];
                        }
                        else
                        {
                            dr["QualCode"] = itemQualCode.Trim();
                            dr["QualDesc"] = "";
                        }
                        dr["CQAID"] = this.txtStaffID.Text;
                        dtTemp.Rows.Add(dr);
                    }
                }
                else
                {//one
                    DataRow dr = dtTemp.NewRow();
                    if (ddlQualification.SelectedValue.Trim().Contains(' '))
                    {
                        dr["QualCode"] = ddlQualification.SelectedValue.Trim().Split(' ')[0];
                        dr["QualDesc"] = ddlQualification.SelectedValue.Trim().Split(' ')[1];
                    }
                    else
                    {
                        dr["QualCode"] = ddlQualification.SelectedValue.Trim();
                        dr["QualDesc"] = "";
                    }
                    dr["CQAID"] = this.txtStaffID.Text;
                    dtTemp.Rows.Add(dr);
                }

                //if (ddlQualification.SelectedItem.Value.Trim().Contains(" "))
                //{
                //    int index = ddlQualification.SelectedItem.Value.IndexOf(" ");
                //    dr["QualCode"] = ddlQualification.SelectedItem.Value.Substring(0, index);
                //}
                //else
                //{
                //    dr["QualCode"] = ddlQualification.SelectedItem.Value;
                //}
                //dr["QualDesc"] = ddlQualification.SelectedItem.Value;
                //dr["CQAID"] = this.txtStaffID.Text;
                //dtTemp.Rows.Add(dr);

            }
            //else
            //{
            //    dr["QualCode"] = "";
            //    dr["QualDesc"] = "";
            //}

            //dr["CQAID"] = this.txtStaffID.Text;
            //dtTemp.Rows.Add(dr);

            DataSet dsTempSave = new DataSet();
            dsTempSave.Tables.Add(dtTemp);
            int nPersonHoldQualKye;
            if (hdnPersonHoldQualKye.Value == null || hdnPersonHoldQualKye.Value.ToString() == string.Empty)
            {
                nPersonHoldQualKye = BLL.SOM.TempData.CacheDataSet(dsTempSave, this.ODMUser.ID, this.ODMUser.Domain);
                hdnPersonHoldQualKye.Value = nPersonHoldQualKye.ToString();
            }
            else
            {
                nPersonHoldQualKye = Convert.ToInt32(hdnPersonHoldQualKye.Value.ToString());
                BLL.SOM.TempData.UpdateCacheData(nPersonHoldQualKye, dsTempSave);
            }

            this.txtQualification.Text = this.ddlQualification.SelectedValue;
            this.hdnPersonHoldQualKye.Value = nPersonHoldQualKye.ToString();
        }

        #endregion

        #region Event

        protected void ddlWorkCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*Comment by jack for 239*/
            //this.AjaxUpdateIsServerChanged();
            if (string.IsNullOrEmpty(Request.QueryString["Destroy"]))
            {
                this.AjaxUpdateIsServerChanged();
            }
            /************************/
            ViewState["SubFlagReqSign"] = "0";
            ViewState["SubFlagProtect"] = "0";
            if (ddlWorkCategory.SelectedIndex == 0)
            {
                //add by Nathan 20150827 U168.4
                //BindWorkSubCategory();
                //CheckWorkCategorySignatureMust(-1);
                ddlSubCategory.Items.Clear();
                //add by Nathan 20150827 U168.4
            }
            else
            {
                string strWorkCategory = ddlWorkCategory.SelectedValue;
                DataView dvWorkSubCategory = new DataView();
                dvWorkSubCategory.Table = ODMS.DAL.SOM.CodeSetup.CDAdmRegSubCategory.GetAllWorkSubCategory(this.LangCode);
                dvWorkSubCategory.RowFilter = "AdmRegCategoryID = " + strWorkCategory;
                BindListControl(this.ddlSubCategory, "AdmRegSubCategoryID", "Description", dvWorkSubCategory.ToTable(), true, "");
                CheckWorkCategorySignatureMust(Convert.ToInt32(strWorkCategory));
            }

            //add by gordon 20150723
            object flagProtect = ViewState["FlagProtect"];
            if (flagProtect != null)
            {
                string strProtect = flagProtect.ToString();
                if (strProtect == "1")
                {
                    emMandatory.Visible = true;
                }
                else
                {
                    emMandatory.Visible = false;
                }
            }
            else
            {
                emMandatory.Visible = false;
            }
        }

        protected void ddlSubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            if (ddlSubCategory.SelectedIndex == 0)
            {
                CheckWorkSubCategorySignatureMust(-1);
            }
            else
            {
                CheckWorkSubCategorySignatureMust(Convert.ToInt32(ddlSubCategory.SelectedValue));
            }
        }


        //U179 add by Edward  2015.08.26 begin
        protected void ImageAddTransNo_Click(object sender, EventArgs e)
        {
            this.txtTransactionNumber.Text = "";

            string TransNo = "";
            DataTable dataTable;
            dataTable = MTRC.ODMS.DAL.SOM.Event.StationEventAdmRegDa.GetEngineeringWorkInfo(this.ODMUser.LocationID.ToString(), this.txtTNNumber.Text, this.txtTransactionNumber.Text).Tables[0];

            for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
            {
                if (!dataTable.Rows[i]["isStation"].ToString().Equals("Y"))
                {
                    dataTable.Rows.RemoveAt(i);
                }
            }

            if (dataTable.Rows.Count > 1)
            {

                TransNo = dataTable.Rows[0]["GrantMasTrxnNo"].ToString().Substring(0, 6);
                this.txtTransactionNumber.Text = TransNo;
            }

        }
        protected void ImageClearTransNo_Click(object sender, EventArgs e)
        {

            this.txtTransactionNumber.Text = "";
        }

        //add by benson 2015.07.13 begin
        protected void btnCopyAllPossession_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            bool IsCopyAllButon = (btn.ID == this.btnCopyAllPossession.ID);

            string tnNo = "";
            if (!string.IsNullOrEmpty(txtTNNumber.Text))
            {
                tnNo = txtTNNumber.Text;
            }
            string TransactionNo = null;
            if (!string.IsNullOrEmpty(txtTransactionNumber.Text))
            {
                TransactionNo = txtTransactionNumber.Text;
            }
            //add by benson 2015.09.08  U190.2 begin
            if (string.IsNullOrEmpty(tnNo) && string.IsNullOrEmpty(TransactionNo))
            {
                ImageAddTransNo_Click(sender, null);
            }
            //add by benson 2015.09.08  U190.2 end
            string locationId = this.ODMUser.LocationID.ToString();
            string thisScript = "ShowDetailsEngineeringWork('" + IsCopyAllButon + "',0);";
            //if (string.IsNullOrEmpty(tnNo) && string.IsNullOrEmpty(TransactionNo))
            //{
            //    //this.ClientScript.RegisterStartupScript(typeof(BasePage), "ShowDetailsEngineeringWork", "<script language='javascript' type='text/javascript'>ShowDetailsEngineeringWork('" + tnNo + "','" + TransactionNo + "','" + stationId + "')</script>");
            //    return;
            //}

            //add by gordon 20150813
            if (string.IsNullOrEmpty(tnNo) && string.IsNullOrEmpty(TransactionNo))
            {
                //to be updated
                return;
            }

            DataSet dsWork = MTRC.ODMS.DAL.SOM.Event.StationEventAdmRegDa.GetEngineeringWorkInfo(locationId, tnNo, TransactionNo);
            if (dsWork.Tables[0].Rows.Count > 0)
            {
                DataRow[] drWork = dsWork.Tables[0].Select("isStation ='Y'");
                if (drWork.Length == 0)
                {
                    string retMsg = this.GetMessage("SOM_WorkNotCurrentStation");//SOM_WorkNotCurrentStation
                    PAlert(retMsg);
                    return;

                }
                else if (drWork.Length == 1)
                {

                    txtTNNumber.Text = drWork[0]["GrantTN"].ToString();
                    txtTransactionNumber.Text = drWork[0]["GrantMasTrxnNo"].ToString();
                    if (IsCopyAllButon)
                    {
                        txtJobLocation.Text = drWork[0]["JobLocation"].ToString();
                    }
                    else
                    {
                        //add by gordon 20150818
                        txtJobLocation.Text = "";
                    }
                    txtJobNature.Text = drWork[0]["JobNature"].ToString();
                    txtJobProtection.Text = drWork[0]["JobProtection"].ToString();
                }
                else
                {
                    ToolkitScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", thisScript, true);
                    //this.ClientScript.RegisterStartupScript(typeof(BasePage), "ShowDetailsEngineeringWork", "<script language='javascript' type='text/javascript'></script>");
                }
            }
            else
            {
                string retMsg = this.GetMessage("SOM_NoEngineeringWork");//SOM_NoEngineeringWork
                PAlert(retMsg);
                return;
            }
        }
        //add by benson 2015.07.13 begin
        protected void btnNew_Click(object sender, EventArgs e)
        {
        }

        protected void btnCopyAsNew_Click(object sender, EventArgs e)
        {
            CopyAsNewSetting();
            Session["AR_FireInitDateTime"] = null;//Add by jack 20151223 U291 The amendment history on isolation time is incorrect.
            btnALEdit.Visible = false;//add by gordon 20160201 - ISU36

            //Comment by gordon 20160215 ISU51
            //add by gordon 20160201 ISU12
            //Log.Logger("After Copy As New Start", 4, this.ODMUser.ID, this.ODMUser.UserGroupName);
            //Log.Logger("hdnAssetLoanMainDataTmpID:" + hdnAssetLoanMainDataTmpID.Value, 4, this.ODMUser.ID, this.ODMUser.UserGroupName);
            //Log.Logger("hdnAssetLoanItemDataTmpID:" + hdnAssetLoanItemDataTmpID.Value, 4, this.ODMUser.ID, this.ODMUser.UserGroupName);
            //Log.Logger("After Copy As New End", 4, this.ODMUser.ID, this.ODMUser.UserGroupName);
            //add end by gordon 20160201
            //Comment end by gordon 20160215 ISU51
        }
        public void setReadOnlyButton(bool isTrue)
        {
            if (isTrue)
            {
                this.mainInfo.Disabled = false;
                this.divFlowMenu.Disabled = false;
                this.btnDeparture.Enabled = true;
                this.btnSaveTop.Enabled = true;
                this.btnNew.Enabled = true;
                this.btnCopyAsNew.Enabled = true;
                this.btnSave.Enabled = true;
            }
            else
            {
                this.mainInfo.Disabled = true;
                this.divFlowMenu.Disabled = true;
                this.btnDeparture.Enabled = false;
                this.btnSaveTop.Enabled = false;
                this.btnNew.Enabled = false;
                this.btnCopyAsNew.Enabled = false;
                this.btnSave.Enabled = false;
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //add by tim 20160701
            string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
            Session[signatureName] = this.ucSignatureNew1.SignatureTemp;
            //end add
            //add by Gordon 2016-02-03 Issue 14  start
            setReadOnlyButton(false);
            //add by Gordon 2016-02-03 Issue 14  end
            //return;
            Button btn = (Button)sender;
            bool IsSaveButon = (btn.ID == this.btnSave.ID);
            // remove by dylan 20151118 for u276 try catch
            //try
            //{
            if (this.SaveModel == 2)
            {
                string LastUpdBy = "";
                int result = MTRC.ODMS.DAL.SOM.Event.StationEventDa.LastUpdataTimeCheck(this.StationEventID, this.ConvertToDateTime(hdnStationEventLastUpdataTime.Value), this.LangCode, ref  LastUpdBy);
                if (result > 0)
                {
                    string.Format("aa{0},{1},{0}", 2, 3);
                    string strMsg = this.GetMessage("SOM_RecordAlreadyUpdataed");
                    //strMsg = strMsg.Replace("{0}", LastUpdBy);
                    strMsg = string.Format(strMsg, LastUpdBy);
                    if (IsSaveButon)
                    {
                        Alert(strMsg);
                    }
                    else
                    {
                        PAlert(strMsg);
                    }
                    //add by Gordon 2016-02-03 Issue 14  start
                    setReadOnlyButton(true);
                    //add by Gordon 2016-02-03 Issue 14  end
                    return;
                }
            }

            //add by jack 20150707 for U50
            //if (CommonData.GetCharVal("SOM_CQAQual_Realtime_Enable").Trim() == "Y")
            //{
            //    SaveQualificationToTempData();
            //}
            // add by dylan 20151110 for add try catch



            int nStationEventID = -1;
            int RequirePasswordStaffInfoID = 0;     //it's mean not updata RequirePasswordStaffInfoID column with SOM_StationEvent table
            string RequirePasswordUserID = "";
            if (!ValidationBeforeSaveOperation(IsSaveButon))
            {
                //add by Gordon 2016-02-03 Issue 14  start
                setReadOnlyButton(true);
                //add by Gordon 2016-02-03 Issue 14  end
                return;
            }

            if (!IsUserValidate())            //or (hdnFlagNeedValit.Value == "5")
            {
                nStationEventID = Save(RequirePasswordUserID, RequirePasswordStaffInfoID);
                //update by gordon 20160218 ISU45
                //SettingAfterSave(IsSaveButon);
                SettingAfterSave(IsSaveButon, nStationEventID);
            }
            else                             //or (hdnFlagNeedValit.Value == "4")
            {
                if (UserValidate(out RequirePasswordUserID, out RequirePasswordStaffInfoID))
                {
                    nStationEventID = Save(RequirePasswordUserID, RequirePasswordStaffInfoID);
                    //update by gordon 20160218 ISU45
                    //SettingAfterSave(IsSaveButon);
                    SettingAfterSave(IsSaveButon, nStationEventID);
                }
                else
                {  //add by Gordon 2016-02-03 Issue 14  start
                    setReadOnlyButton(true);
                    //add by Gordon 2016-02-03 Issue 14  end
                    return;
                }
            }
            ExportSetting(false); //1467
            //}
            //catch (Exception ex)
            //{
            //    APJ.Util.Log.WindowLog.Log(this.GetLabel("SOM_AdmissionRegistryExceptionTitle", true) + ex.Message.Replace('"', '\''), APJ.Util.Log.LogType.Error, this.User.Identity.Name);
            //    this.PAlert(this.GetMessage("SOM_AdmissionRegistryException"));
            //}
            //add by Gordon 2016-02-03 Issue 14  start
            setReadOnlyButton(true);
            //add by Gordon 2016-02-03 Issue 14  end
            //U46
            string IfTranferSucceed = "IfTranferSucceed" + this.StationEventID;
            Session[IfTranferSucceed] = "";
            Session["TranferTime"] = null; //add by jack 20151207 u288 clear session when save data success
            Session["AR_FireInitDateTime"] = null;//Add by jack 20151223 U291 The amendment history on isolation time is incorrect.
        }

        //Begin Edward U46 2015-08-12 It shows this behaviour before save but both items are transferred after save keep the tansfer function in new SOMS(SCAS has,old no):transfer to another person
        protected void btnRefreshFireRowAfterTransfer_Click(object sender, EventArgs e)
        {
            int nFireSystemKey = Convert.ToInt32(hdnFireSystemKey.Value);
            DataTable dtFireGirdList = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.GetFireGridListByKey(nFireSystemKey, this.LangCode);
            grdFireSystem.DataSource = dtFireGirdList.DefaultView;
            grdFireSystem.DataBind();
        }
        //End Edward 2015-08-12 U46

        protected void txtStaffID_TextChanged(object sender, EventArgs e)
        {
            //Issue U152  By Edward 2015/08/26
            if (!txtStaffID.Enabled)
            {
                return;
            }

            //Issue U12:Add By Gordon 2015/05/22
            string script = string.Empty;
            string needDisabled = "false";
            //----------------------------------

            //for local contrator
            if (this.hdnIsValueFromPopup.Value.Trim() == "Y" && this.hdnStaffType.Value == "3")
            {
                string company = this.hdnDepartmentCompany.Value;
                List<string> listCompany = new List<string>();
                listCompany.Add(company);
                BindOUCompany(listCompany);

                this.txtDepartmentCompany.Text = company;
                List<string> listQualification = new List<string>();
                BindQualification(listQualification);

                hdnStaffType_ServerChange(null, null);

                //Set Cursor U12
                needDisabled = "true";
                script = "SetCursor('');if(document.getElementById('txtStaffID')){staffid=document.getElementById('txtStaffID').value;}SetStaffInfoEnabled(false," + needDisabled + ");";
                ToolkitScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", script, true);
            }
            else
            {
                this.AjaxUpdateIsServerChanged();
                //check input data, use NL's method
                hdnStationEventPersonID.Value = "";
                //hdnStaffType.Value = "";            
                //update by benson 2015.07.27  U102 begin
                if (this.hdnIsValueFromPopupQualification.Value.Trim() == "Y")  //is open from PopupResponsibilityTransfer Form
                {
                    this.ucSignatureNew1.IsNeedSignAgain = false;
                    //this.ucSignatureArrival.IsNeedSignAgain = false;
                    //ucSignatureArrivalBottom.IsNeedSignAgain = false;
                }
                else
                {
                    this.ucSignatureNew1.IsNeedSignAgain = true;
                    //this.ucSignatureArrival.IsNeedSignAgain = true;
                    //ucSignatureArrivalBottom.IsNeedSignAgain = true;
                    //begin updata by hzx,on 20090115
                    hdnPersonHoldQualKye.Value = "";
                    this.txtQualification.Text = "";
                    //end
                }

                //if (ucSignatureDeparture.GetSignatureFullFileName(2).ToString() != string.Empty)
                //{
                //    this.ucSignatureDeparture.IsNeedSignAgain = true;
                //    ucSignatureDepartureBottom.IsNeedSignAgain = true;
                //}
                //update by benson 2015.07.27  U102 end
                //this.ucSignatureDeparture.InitUCSignatureValue(2,1,"");
                string staffID = this.txtStaffID.Text.Trim();

                //begin:add by hzx,20090105
                int nExtPartyStaffSnapShotID = 0;
                if (this.hdnIsValueFromPopup.Value.Trim() == "Y")  //is open from Search popup Form
                {
                    if (this.hdnStaffType.Value.Trim() == "2" || this.hdnStaffType.Value.Trim() == "3")
                    {
                        int.TryParse(this.hdnExtPartyStaffSnapShotID.Value.Trim(), out nExtPartyStaffSnapShotID);
                    }
                }
                this.hdnExtPartyStaffSnapShotID.Value = "";
                //end

                if (staffID != string.Empty)
                {
                    //edit by hjh 20120519 for DataReader not close
                    //update by jack 20150701 for U50
                    #region Comment
                    //using (System.Data.SqlClient.SqlDataReader dr = MTRC.ODMS.DAL.SOM.CodeSetup.CdStaffInfo.SearchStaffInfo(staffID, this.LangCode, nExtPartyStaffSnapShotID))
                    //{
                    //    if (dr.Read())
                    //    {
                    //        bool isExists = (dr["FlagStaffORContractor"].ToString() == "1" ? true : false);
                    //        if (isExists)
                    //        {
                    //            //eventPersonTypeID=1,2,3, staff, CQA contractor, Station contractor
                    //            string eventPersonTypeID = dr["EventPersonTypeID"].ToString();  //huangyao 20100326 issue 1399
                    //            //if (dr["EventPersonTypeID"].ToString() == "5")
                    //            if (eventPersonTypeID == "5")
                    //            {
                    //                //exists, but not a valid staff or obsolete, or status set to T
                    //                this.txtStaffID.Text = "";
                    //                this.PAlert(this.GetMessage("SOM_SelectedAnVoidStaffMsg"));

                    //                //Issue U12:Add By Gordon 2015/05/22
                    //                //Set Cursor U12
                    //                script = "SetCursor('');if(document.getElementById('txtStaffID')){staffid=document.getElementById('txtStaffID').value;}SetStaffInfoEnabled(false,false);";
                    //                ToolkitScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", script, true);
                    //                return;
                    //            }
                    //            else
                    //            {
                    //                //Issue U12:Add By Gordon 2015/05/22
                    //                needDisabled = "true";

                    //                hdnStaffType.Value = eventPersonTypeID;
                    //                hdnStaffOrExtPartyID.Value = dr["StaffOrExtPartyID"].ToString();
                    //                this.hdnStaffName.Value = dr["StaffName"].ToString();
                    //                this.hdnDepartmentCompany.Value = dr["DepartmentCompany"].ToString();
                    //                this.hdnOrganizationUnit.Value = dr["OrganizationUnit"].ToString();
                    //                this.hdnContactNo.Value = dr["Tel"].ToString();
                    //                this.hdnExtPartyStaffSnapShotID.Value = Util.StringFromDB(dr["ExtPartyStaffSnapShotID"]); //add by hzx 20090105 for change 0824
                    //            }
                    //        }
                    //        else
                    //        {
                    //            //-Ad-hoc 
                    //            hdnStaffType.Value = "4";
                    //            hdnStaffOrExtPartyID.Value = "";

                    //            this.hdnStaffName.Value = "";
                    //            this.hdnDepartmentCompany.Value = "";
                    //            this.hdnOrganizationUnit.Value = "";
                    //            this.hdnContactNo.Value = "";
                    //        }
                    //    }
                    //    hdnStaffType_ServerChange(null, EventArgs.Empty);
                    #endregion
                    if (CommonData.GetCharVal("SOM_CQAQual_Realtime_Enable").Trim() == "Y")
                    {
                        try
                        {
                            #region Realtime Interface
                            List<string> ouCompany = new List<string>();
                            List<string> qualification = new List<string>();
                            string qualTypeCode = CommonData.GetStrVal("SOM_CQAQual_QualTypeCode").Trim();
                            DataSet ds_CQA = MTRC.ODMS.DAL.SOM.CodeSetup.CdStaffInfo.GetCQASData(staffID, qualTypeCode);
                            DataTable dt_CQA = ds_CQA.Tables[0];
                            using (System.Data.DataSet ds = MTRC.ODMS.DAL.SOM.CodeSetup.CdStaffInfo.SearchStaffInfo(staffID, this.LangCode, nExtPartyStaffSnapShotID, dt_CQA)) //update by jack 20150701 for U50
                            {
                                if (ds.Tables[0].Rows.Count > 0)
                                {
                                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                    {
                                        //bool isExists = (dr["FlagStaffORContractor"].ToString() == "1" ? true : false);
                                        bool isExists = (ds.Tables[0].Rows[i]["PersonType"].ToString() == "1" || ds.Tables[0].Rows[i]["PersonType"].ToString() == "2" ? true : false);
                                        if (isExists)
                                        {
                                            string eventPersonTypeID = ds.Tables[0].Rows[i]["PersonType"].ToString();  //add by jack 20150701 for u50

                                            //Issue U12:Add By Gordon 2015/05/22
                                            needDisabled = "true";

                                            //Add By Gordon 20150702 U103
                                            if (eventPersonTypeID != "3")
                                            {
                                                this.txtContactNo.Text = "";
                                            }

                                            this.oldCompany.Style.Add("display", "none");
                                            this.newCompany.Style.Add("display", "block");
                                            this.oldQualification.Style.Add("display", "none");
                                            this.newQualification.Style.Add("display", "block");

                                            hdnStaffType.Value = eventPersonTypeID;
                                            this.hdnStaffName.Value = ds.Tables[0].Rows[i]["StaffName"].ToString();
                                            this.hdnDepartmentCompany.Value = ds.Tables[0].Rows[i]["OrganizationUnitDesc"].ToString();

                                            if (!ouCompany.Contains(ds.Tables[0].Rows[i]["OrganizationUnitDesc"].ToString()) && !string.IsNullOrEmpty(ds.Tables[0].Rows[i]["OrganizationUnitDesc"].ToString()))
                                            {
                                                ouCompany.Add(ds.Tables[0].Rows[i]["OrganizationUnitDesc"].ToString());
                                            }

                                            if (!qualification.Contains(ds.Tables[0].Rows[i]["QUALCD"].ToString() + " " + ds.Tables[0].Rows[i]["QUALSHORTDESC"].ToString()) && !string.IsNullOrEmpty(ds.Tables[0].Rows[i]["QUALCD"].ToString()))
                                            {
                                                qualification.Add(ds.Tables[0].Rows[i]["QUALCD"].ToString() + " " + ds.Tables[0].Rows[i]["QUALSHORTDESC"].ToString());
                                            }
                                        }
                                        else
                                        {
                                            //-Ad-hoc 
                                            hdnStaffType.Value = "4";
                                            hdnStaffOrExtPartyID.Value = "";

                                            this.hdnStaffName.Value = "";
                                            this.hdnDepartmentCompany.Value = "";
                                            this.hdnOrganizationUnit.Value = "";
                                            this.hdnContactNo.Value = "";

                                            //Add By Gordon 20150702 U103
                                            this.txtContactNo.Text = "";
                                        }
                                    }

                                }
                                else
                                {
                                    //-Ad-hoc 
                                    hdnStaffType.Value = "4";
                                    hdnStaffOrExtPartyID.Value = "";

                                    this.hdnStaffName.Value = "";
                                    this.hdnDepartmentCompany.Value = "";
                                    this.hdnOrganizationUnit.Value = "";
                                    this.hdnContactNo.Value = "";

                                    //Add By Gordon 20150702 U103
                                    this.txtContactNo.Text = "";
                                }
                                //add by jack 20150701 for U50.2
                                BindOUCompany(ouCompany);
                                //add by jack 20150702 for U50.3
                                BindQualification(qualification);
                                hdnStaffType_ServerChange(null, EventArgs.Empty);

                            }
                            #endregion

                            //test excecption
                            //int a = 10;
                            //int b = 0;
                            //int c = a / b;
                        }
                        catch (Exception ex)
                        {

                            APJ.Util.Log.WindowLog.Log(this.GetMessage("SOM_CQASException") + ex.Message.Replace('"', '\''), APJ.Util.Log.LogType.Error, this.User.Identity.Name); //Comment by jack 20151030 for u272
                            // edit by dylan 20151111 for u276 add try catch
                            //this.PAlert(this.GetMessage("SOM_CQASException") + ex.Message.Replace('"', '\''));
                            this.PAlert(this.GetMessage("SOM_CQASException"));
                            if (CommonData.GetCharVal("SOM_CQAQual_Batch_Enable").Trim() == "Y")
                            {
                                this.oldCompany.Style.Add("display", "block");
                                this.newCompany.Style.Add("display", "none");
                                this.oldQualification.Style.Add("display", "block");
                                this.newQualification.Style.Add("display", "none");
                                #region Bath job
                                using (System.Data.SqlClient.SqlDataReader dr = MTRC.ODMS.DAL.SOM.CodeSetup.CdStaffInfo.SearchStaffInfo(staffID, this.LangCode, nExtPartyStaffSnapShotID))
                                {
                                    if (dr.Read())
                                    {
                                        bool isExists = (dr["FlagStaffORContractor"].ToString() == "1" ? true : false);
                                        if (isExists)
                                        {
                                            //eventPersonTypeID=1,2,3, staff, CQA contractor, Station contractor
                                            string eventPersonTypeID = dr["EventPersonTypeID"].ToString();  //huangyao 20100326 issue 1399
                                            //if (dr["EventPersonTypeID"].ToString() == "5")
                                            if (eventPersonTypeID == "5")
                                            {
                                                //exists, but not a valid staff or obsolete, or status set to T
                                                this.txtStaffID.Text = "";
                                                this.PAlert(this.GetMessage("SOM_SelectedAnVoidStaffMsg"));

                                                //Add By Gordon 20150702 U103
                                                this.txtContactNo.Text = "";

                                                //Issue U12:Add By Gordon 2015/05/22
                                                //Set Cursor U12
                                                script = "SetCursor('');if(document.getElementById('txtStaffID')){staffid=document.getElementById('txtStaffID').value;}SetStaffInfoEnabled(false,false);";
                                                ToolkitScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", script, true);
                                                return;
                                            }
                                            else
                                            {
                                                //Issue U12:Add By Gordon 2015/05/22
                                                needDisabled = "true";

                                                if (eventPersonTypeID != "3")
                                                {
                                                    //Add By Gordon 20150702 U103
                                                    this.txtContactNo.Text = "";
                                                }

                                                hdnStaffType.Value = eventPersonTypeID;
                                                hdnStaffOrExtPartyID.Value = dr["StaffOrExtPartyID"].ToString();
                                                this.hdnStaffName.Value = dr["StaffName"].ToString();
                                                this.hdnDepartmentCompany.Value = dr["DepartmentCompany"].ToString();
                                                this.hdnOrganizationUnit.Value = dr["OrganizationUnit"].ToString();
                                                this.hdnContactNo.Value = dr["Tel"].ToString();
                                                this.hdnExtPartyStaffSnapShotID.Value = Util.StringFromDB(dr["ExtPartyStaffSnapShotID"]); //add by hzx 20090105 for change 0824
                                            }
                                        }
                                        else
                                        {
                                            //-Ad-hoc 
                                            hdnStaffType.Value = "4";
                                            hdnStaffOrExtPartyID.Value = "";

                                            this.hdnStaffName.Value = "";
                                            this.hdnDepartmentCompany.Value = "";
                                            this.hdnOrganizationUnit.Value = "";
                                            this.hdnContactNo.Value = "";

                                            //Add By Gordon 20150702 U103
                                            this.txtContactNo.Text = "";
                                        }
                                    }
                                    hdnStaffType_ServerChange(null, EventArgs.Empty);
                                }
                                #endregion
                            }
                            else
                            {
                                hdnStaffType.Value = "4";
                                hdnStaffOrExtPartyID.Value = "";
                                this.hdnStaffName.Value = "";
                                this.hdnDepartmentCompany.Value = "";
                                this.hdnOrganizationUnit.Value = "";
                                this.hdnContactNo.Value = "";
                                //Add By Gordon 20150702 U103
                                this.txtContactNo.Text = "";
                                this.txtQualification.Text = string.Empty;
                                hdnStaffType_ServerChange(null, EventArgs.Empty);
                            }
                        }
                    }
                    else
                    {
                        this.oldCompany.Style.Add("display", "block");
                        this.newCompany.Style.Add("display", "none");
                        this.oldQualification.Style.Add("display", "block");
                        this.newQualification.Style.Add("display", "none");
                        #region Bath job
                        using (System.Data.SqlClient.SqlDataReader dr = MTRC.ODMS.DAL.SOM.CodeSetup.CdStaffInfo.SearchStaffInfo(staffID, this.LangCode, nExtPartyStaffSnapShotID))
                        {
                            if (dr.Read())
                            {
                                bool isExists = (dr["FlagStaffORContractor"].ToString() == "1" ? true : false);
                                if (isExists)
                                {
                                    //eventPersonTypeID=1,2,3, staff, CQA contractor, Station contractor
                                    string eventPersonTypeID = dr["EventPersonTypeID"].ToString();  //huangyao 20100326 issue 1399
                                    //if (dr["EventPersonTypeID"].ToString() == "5")
                                    if (eventPersonTypeID == "5")
                                    {
                                        //exists, but not a valid staff or obsolete, or status set to T
                                        this.txtStaffID.Text = "";
                                        this.PAlert(this.GetMessage("SOM_SelectedAnVoidStaffMsg"));

                                        //Add By Gordon 20150702 U103
                                        this.txtContactNo.Text = "";

                                        //Issue U12:Add By Gordon 2015/05/22
                                        //Set Cursor U12
                                        script = "SetCursor('');if(document.getElementById('txtStaffID')){staffid=document.getElementById('txtStaffID').value;}SetStaffInfoEnabled(false,false);";
                                        ToolkitScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", script, true);
                                        return;
                                    }
                                    else
                                    {
                                        //Issue U12:Add By Gordon 2015/05/22
                                        needDisabled = "true";

                                        if (eventPersonTypeID != "3")
                                        {
                                            //Add By Gordon 20150702 U103
                                            this.txtContactNo.Text = "";
                                        }

                                        hdnStaffType.Value = eventPersonTypeID;
                                        hdnStaffOrExtPartyID.Value = dr["StaffOrExtPartyID"].ToString();
                                        this.hdnStaffName.Value = dr["StaffName"].ToString();
                                        this.hdnDepartmentCompany.Value = dr["DepartmentCompany"].ToString();
                                        this.hdnOrganizationUnit.Value = dr["OrganizationUnit"].ToString();
                                        this.hdnContactNo.Value = dr["Tel"].ToString();
                                        this.hdnExtPartyStaffSnapShotID.Value = Util.StringFromDB(dr["ExtPartyStaffSnapShotID"]); //add by hzx 20090105 for change 0824
                                    }
                                }
                                else
                                {
                                    //-Ad-hoc 
                                    hdnStaffType.Value = "4";
                                    hdnStaffOrExtPartyID.Value = "";

                                    this.hdnStaffName.Value = "";
                                    this.hdnDepartmentCompany.Value = "";
                                    this.hdnOrganizationUnit.Value = "";
                                    this.hdnContactNo.Value = "";

                                    //Add By Gordon 20150702 U103
                                    this.txtContactNo.Text = "";
                                }
                            }
                            hdnStaffType_ServerChange(null, EventArgs.Empty);
                        }
                        #endregion
                    }
                }
                else
                {
                    hdnStaffType.Value = "4";
                    hdnStaffOrExtPartyID.Value = "";
                    this.hdnStaffName.Value = "";
                    this.hdnDepartmentCompany.Value = "";
                    this.hdnOrganizationUnit.Value = "";
                    this.hdnContactNo.Value = "";
                    //Add By Gordon 20150702 U103
                    this.txtContactNo.Text = "";
                    this.txtQualification.Text = string.Empty;
                    hdnStaffType_ServerChange(null, EventArgs.Empty);
                }

                //Issue U12:Add By Gordon 2015/05/22
                //Set Cursor U12
                script = "SetCursor('');if(document.getElementById('txtStaffID')){staffid=document.getElementById('txtStaffID').value;}SetStaffInfoEnabled(false," + needDisabled + ");";
                ToolkitScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", script, true);

            }

            if (this.SaveModel == 2)
            {
                oldCompany.Style.Add("display", "block");
                newCompany.Style.Add("display", "none");

                if (CommonData.GetCharVal("SOM_CQAQual_Realtime_Enable").Trim() == "Y")
                {
                    newQualification.Style.Add("display", "block");
                    oldQualification.Style.Add("display", "none");
                }
                else
                {
                    oldQualification.Style.Add("display", "block");
                    newQualification.Style.Add("display", "none");
                }

                this.txtQualification.Enabled = false;
                this.btnMoreQualification.Enabled = false;
                this.txtStaffName.Enabled = false;
                this.txtDepartmentCompany.Enabled = false;
                this.ddlQualification.Enabled = false;
            }
        }

        protected void hdnStaffType_ServerChange(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            txtStaffName.Text = hdnStaffName.Value;
            txtDepartmentCompany.Text = hdnDepartmentCompany.Value;
            //add by jack 20150701 for U50

            txtOrganizationUnit.Text = hdnOrganizationUnit.Value;
            //txtContactNo.Text = hdnContactNo.Value;

            bool canEditStaffInfo = false;
            if (hdnStaffType.Value == "1")
            {
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/SOM/StaffType_Staff.gif";
                this.imgStaffType.ToolTip = hdnStaffTypeTooltip1.Value;
                canEditStaffInfo = false;
                //lblMustInput.Visible = true;  --alter by hzx,on 20090206
                btnMoreQualification.Visible = true;
            }
            else if (hdnStaffType.Value == "2")
            {
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/SOM/StaffType_CQAContractor.gif";
                this.imgStaffType.ToolTip = hdnStaffTypeTooltip2.Value;
                canEditStaffInfo = false;
                //lblMustInput.Visible = true;   --alter by hzx,on 20090206
                btnMoreQualification.Visible = true;
            }
            else if (hdnStaffType.Value == "3")
            {
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/SOM/StaffType_StationContractor.gif";
                this.imgStaffType.ToolTip = hdnStaffTypeTooltip3.Value;
                canEditStaffInfo = false;
                //lblMustInput.Visible = false;  --alter by hzx,on 20090206
                btnMoreQualification.Visible = false;
            }
            else if (hdnStaffType.Value == "4")
            {
                canEditStaffInfo = true;
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/SOM/StaffType_AddHoc.gif";
                this.imgStaffType.ToolTip = hdnStaffTypeTooltip4.Value;
                //lblMustInput.Visible = false;  --alter by hzx,on 20090206
                btnMoreQualification.Visible = false;
                hdnStaffOrExtPartyID.Value = "";

                this.oldCompany.Style.Add("display", "block");
                this.newCompany.Style.Add("display", "none");
            }
            else
            {
                canEditStaffInfo = true;
                this.imgStaffType.ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
                hdnStaffOrExtPartyID.Value = "";
            }
            if (SaveModel == 1)
            {
                this.txtStaffName.Enabled = canEditStaffInfo;
                this.txtDepartmentCompany.Enabled = canEditStaffInfo;
            }
            else
            {
                this.txtStaffName.Enabled = false;
                //this.txtDepartmentCompany.Enabled = canEditStaffInfo;
                this.txtDepartmentCompany.Enabled = false; //add by jack 20151207 for U288 fixed OU / Company should be disabled after clicking ��Confirm�� button in Transfer popup window

            }
        }

        protected void hdnAmendTimeVal_ServerChange(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            //update by benson 2015-10-24 u253 begin
            //if (SaveModel == 1)
            //{
            //    this.dtbArrivalTime.SetDateTime(this.ConvertToDateTime(hdnArrivalDate.Value + " " + hdnArrivalTime.Value));
            //}
            //else
            //{
            //    lblArrivalTime.Text = hdnArrivalDate.Value + " " + hdnArrivalTime.Value;
            //}
            lblArrivalTime.Text = hdnArrivalDate.Value + " " + hdnArrivalTime.Value;

            //add by gordon 20160216 ISU51
            //BLL.SOM.Log.Logger("AR->hdnAmendTimeVal_ServerChange->lblArrivalTime:" + lblArrivalTime.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

            txtEstimatedCompletionTime_TextChanged(null, null);
            //update by benson 2015-10-24 u253 end
            //update by benson 2015.07.27  U102 begin
            //txtChangeArrivalReason.Text = hdnChangeArrivalReason.Value;
            //update by benson 2015.07.27  U102 end

        }

        protected void btnTransferResponsibility_Click(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
        }

        protected void btnTNNumberMore_Click(object sender, EventArgs e)
        {

        }

        protected void txtEstimatedCompletionTime_TextChanged(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            //update by benson 2015-10-24 u253 begin
            //DateTime dt = new DateTime();
            //if (this.SaveModel == 1)
            //{
            //    dt = this.dtbArrivalTime.GetDateTime();
            //}
            //else
            //{
            //    dt = this.ConvertToDateTime(this.lblArrivalTime.Text.Trim());
            //}
            //update by benson 2015-10-24 u253 end
            DateTime dt = this.ConvertToDateTime(this.lblArrivalTime.Text.Trim());
            //--------------------------------Change validation method: Delete By Gordon 2015/05/21
            //if (txtEstimatedCompletionTime.Text.Trim() != string.Empty)
            //{
            //    //SHould use regx to judge the input data format whether or not match up the right format, #.#, 1 bit decimal
            //    string matchStr = @"^[0-9]+(.[0-9]{1})?$";
            //    System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex(matchStr);
            //    if (regx.IsMatch(txtEstimatedCompletionTime.Text.Trim()))
            //    {
            //        double hrs = 0d;
            //        double.TryParse(txtEstimatedCompletionTime.Text.Trim(), out hrs);
            //        dt = dt.AddHours(hrs);
            //        this.lblShouldCompletionTime.Text = this.FormatDateTime(dt, true);
            //    }
            //    else
            //    {
            //        //this.Alert("Input data format error, should input one bit decimal!");
            //        this.PAlert(this.GetMessage("SOM_EstimateCompletionDateTimeHrsCheck"), 0, this.txtEstimatedCompletionTime);
            //        this.txtEstimatedCompletionTime.Text = "0";
            //    }
            //}

            if (txtEstimatedCompletionTime.Text.Trim() != string.Empty)
            {
                double hrs = 0d;
                double.TryParse(txtEstimatedCompletionTime.Text.Trim(), out hrs);
                dt = dt.AddHours(hrs);
                this.lblShouldCompletionTime.Text = this.FormatDateTime(dt, true);
                //add by benson 2015-09-07 begin
                this.IsChangeWrkHour = 1;
                //add by benson 2015-09-07 end
            }
            //----------------------------------------------------------------------------------------
        }

        protected void chkHandoverCheck_CheckedChanged(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            if (chkHandoverCheck.Checked == true)
            {
                txtHandoverCheckDetail.Enabled = true;
            }
            else
            {
                txtHandoverCheckDetail.Text = "";
                txtHandoverCheckDetail.Enabled = false;
            }
        }

        protected void hdnTransferResponsibilityKey_ServerChange(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            int nTransferResponsibilityKey = Convert.ToInt32(hdnTransferResponsibilityKey.Value);
            DataTable dtTransferResponsibility = BLL.SOM.TempData.GetCacheData(nTransferResponsibilityKey).Tables[0];
            hdnStationEventPersonID.Value = "";

            hdnStaffType.Value = dtTransferResponsibility.Rows[0]["StaffType"].ToString();
            hdnStaffOrExtPartyID.Value = dtTransferResponsibility.Rows[0]["StaffOrExtPartyID"].ToString();
            hdnStaffName.Value = dtTransferResponsibility.Rows[0]["StaffName"].ToString();
            hdnDepartmentCompany.Value = dtTransferResponsibility.Rows[0]["Company"].ToString();
            hdnContactNo.Value = dtTransferResponsibility.Rows[0]["Tel"].ToString();
            hdnOrganizationUnit.Value = dtTransferResponsibility.Rows[0]["OrgUnit"].ToString();

            txtStaffID.Text = dtTransferResponsibility.Rows[0]["StaffID"].ToString();
            txtStaffName.Text = dtTransferResponsibility.Rows[0]["StaffName"].ToString();
            txtDepartmentCompany.Text = dtTransferResponsibility.Rows[0]["Company"].ToString();
            txtContactNo.Text = dtTransferResponsibility.Rows[0]["Tel"].ToString();
            txtOrganizationUnit.Text = dtTransferResponsibility.Rows[0]["OrgUnit"].ToString();

            /* Comment by jack 20150822 for qualification */
            //txtQualification.Text = dtTransferResponsibility.Rows[0]["Qualification"].ToString();
            if (this.oldQualification.Style["display"] == "none")
            {
                /**Comment by jack 20151009 for U170**/
                #region comment
                //add by gordon 20150827 U170.5
                //if (dtTransferResponsibility.Rows.Count > 0 && this.newQualification.Style["display"] == "block" && this.oldQualification.Style["display"] == "none")
                //{
                //    if (!string.IsNullOrEmpty(dtTransferResponsibility.Rows[0]["Qualification"].ToString()))
                //    {
                //        List<string> listQualification = new List<string>();
                //        DataTable dtQualMas = CDQualMas.GetAllCDQualMas().Tables[0];
                //        DataRow[] dr = dtQualMas.Select("QualCode='" + dtTransferResponsibility.Rows[0]["Qualification"].ToString() + "'");
                //        string qualDesc = string.Empty;
                //        if (dr.Length > 0)
                //        {
                //            qualDesc = dr[0]["QualDesc"].ToString();
                //        }
                //        listQualification.Add((dtTransferResponsibility.Rows[0]["Qualification"].ToString() + " " + qualDesc).Trim());
                //        BindQualification(listQualification);
                //        dtQualMas.Dispose();
                //    }
                //    else
                //    {
                //        ddlQualification.Items.Clear();
                //        ListItem item = new ListItem();
                //        item.Text = this.GetMessage("SOM_QualificationNotFound");
                //        item.Value = "";
                //        ddlQualification.Items.Add(item);
                //        ddlQualification.SelectedIndex = 0;
                //    }
                //}
                #endregion
                if (dtTransferResponsibility.Rows.Count > 0 && this.newQualification.Style["display"] == "block" && this.oldQualification.Style["display"] == "none")
                {
                    if (!string.IsNullOrEmpty(dtTransferResponsibility.Rows[0]["Qualification"].ToString()))
                    {
                        if (hdnStatus.Value == "1")
                        {
                            ddlQualification.Items.Clear();
                            List<string> qualSource = GetQual();
                            string listItemString = "";
                            if (qualSource.Count > 0)
                            {
                                string qualification = string.Empty;
                                foreach (string qual in qualSource)
                                {
                                    if (qual.StartsWith(dtTransferResponsibility.Rows[0]["Qualification"].ToString()))
                                    {
                                        ddlQualification.Items.Remove(ddlQualification.SelectedItem);
                                        listItemString = qual;
                                        break;
                                    }
                                }

                                if (string.IsNullOrEmpty(listItemString))
                                {
                                    ddlQualification.Items.Clear();
                                }

                                if (string.IsNullOrEmpty(ddlQualification.SelectedValue))
                                {
                                    ddlQualification.Items.Remove(ddlQualification.SelectedItem);
                                }

                                ddlQualification.Items.Add(new ListItem("", ""));
                                foreach (string qual in qualSource)
                                {
                                    ddlQualification.Items.Add(new ListItem(qual, qual));
                                }

                                ListItem li = ddlQualification.Items.FindByText(listItemString);
                                li.Selected = true;
                            }
                        }
                    }
                    else
                    {
                        ddlQualification.Items.Clear();
                        ListItem item = new ListItem();
                        item.Text = this.GetMessage("SOM_QualificationNotFound");
                        item.Value = "";
                        ddlQualification.Items.Add(item);
                        ddlQualification.SelectedIndex = 0;
                    }
                }
                /********************************************************************************************************/
            }
            else
            {
                txtQualification.Text = dtTransferResponsibility.Rows[0]["Qualification"].ToString();
            }
            /**********************************************/
            //update by benson 2015.07.27 begin
            this.ucSignatureNew1.InitUCSignatureValue(1, Convert.ToInt32(dtTransferResponsibility.Rows[0]["SignType"].ToString()), dtTransferResponsibility.Rows[0]["SignFileName"].ToString());
            //ucSignatureNew1.InitUCSignatureValue(1, Convert.ToInt32(dtTransferResponsibility.Rows[0]["SignType"].ToString()), dtTransferResponsibility.Rows[0]["SignFileName"].ToString());
            //if (ucSignatureNew1.GetSignatureFullFileName(2).ToString() != string.Empty)
            //{
            //    this.ucSignatureNew1.IsNeedSignAgain = true;
            //    //ucSignatureNew1.IsNeedSignAgain = true;
            //}
            //update by benson 2015.07.27 end
            //ucSignatureDeparture.InitUCSignatureValue(2, 1, "");
        }

        protected void hdnTransferChange_ServerChange(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            if (hdnTransferChange.Value != "0")
            {
                hdnTransferChange.Value = "0";
                hdnTransferResponsibilityKey_ServerChange(null, EventArgs.Empty);
            }
        }

        protected void grdFireSystem_NeedDataBind()
        {
            SettingFireGridByDataBind();
        }

        protected void grdFireSystem_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string strAction = "Edit";
                string strParentStationEventID = this.StationEventID.ToString();
                string strParentEvenNo = lblRegistryNumber.Text.Trim();

                //----------------End Get quest parameters---------------

                string tempID = "";
                if (this.hdnFireSystemKey.Value.Trim().Length < 1)
                {
                    tempID = "-1";
                }
                else
                {
                    tempID = this.hdnFireSystemKey.Value;
                }

                string txtStaffID = this.txtStaffID.Text;
                string lblIsolationDateTime = "";

                if (this.lblArrivalTime.Text.Length > 0)
                {
                    lblIsolationDateTime = this.lblArrivalTime.Text;
                }

                string imgRequesSrc = this.imgStaffType.ImageUrl;
                string txtRequestByName = "";

                if (this.txtStaffName.Text.Length > 0)
                {
                    txtRequestByName = this.txtStaffName.Text;
                }

                string txtRequestByDept = "";
                if (this.txtDepartmentCompany.Text.Trim().Length > 0)
                {
                    txtRequestByDept = this.txtDepartmentCompany.Text;
                    //Begin U46 Begin Edward Update 2015-08-12
                    txtRequestByDept = Microsoft.JScript.GlobalObject.escape(txtRequestByDept);
                    //end
                }

                string txtRequestByOU = "";
                if (this.txtOrganizationUnit.Text.Trim().Length > 0)
                {
                    txtRequestByOU = this.txtOrganizationUnit.Text;
                }

                string txtRequestByContactNumber = "";
                if (this.txtContactNo.Text.Trim().Length > 0)
                {
                    txtRequestByContactNumber = this.txtContactNo.Text;
                }

                string txtIsolationDuration = "";
                if (this.txtEstimatedCompletionTime.Text.Trim().Length > 0)
                {
                    txtIsolationDuration = this.txtEstimatedCompletionTime.Text;
                }

                string lblEstimatedIsolationDate = this.lblShouldCompletionTime.Text;

                string txtHandoverNote = "";
                if (this.txtHandoverCheckDetail.Text.Trim().Length > 0)
                {
                    txtHandoverNote = this.txtHandoverCheckDetail.Text;
                }

                int chkHandoverCheck = 0;
                if (this.chkHandoverCheck.Checked)
                {
                    //chkHandoverCheck
                    chkHandoverCheck = 1;
                }

                int hdnStaffType = 3;
                if (this.hdnStaffType.Value.Trim().Length > 0)
                {
                    hdnStaffType = Convert.ToInt16(this.hdnStaffType.Value.Trim());
                }

                string hdnInitDateTime = "";
                if (this.hdnArrivalTimePrototype.Value.Trim().Length > 0)
                {
                    hdnInitDateTime = this.hdnArrivalTimePrototype.Value;
                }

                string hdnRequestStaffOrExtPartyID = "";
                if (this.hdnStaffOrExtPartyID.Value.Trim().Length > 0)
                {
                    hdnRequestStaffOrExtPartyID = this.hdnStaffOrExtPartyID.Value;
                }

                string strtempID = "-1";
                if (hdnFireSystemKey.Value.Trim() != string.Empty)
                {
                    strtempID = hdnFireSystemKey.Value.Trim();
                }

                //----------------End Get quest parameters---------------

                ((Image)(e.Row.Cells[9].FindControl("imgEdit"))).ToolTip = this.GetLabel("COM_Edit", false);
                ((ImageButton)(e.Row.Cells[10].FindControl("imgDelete"))).ToolTip = this.GetLabel("COM_Delete", false);
                ((Image)(e.Row.Cells[9].FindControl("imgEdit"))).Enabled = true;
                string strStationEventID = grdFireSystem.DataKeys[e.Row.RowIndex]["StationEventID"].ToString();

                //add by gordon 20150811 U147
                ((Image)(e.Row.Cells[9].FindControl("imgEdit"))).Attributes.Add("KeyEventID", strStationEventID);

                if (Convert.ToInt32(strStationEventID) > 0)
                {
                    ((Image)(e.Row.Cells[6].FindControl("imgSaveStatus"))).ImageUrl = Request.ApplicationPath + "/Images/SOM/SavedStatus.gif";
                    ((Image)(e.Row.Cells[6].FindControl("imgSaveStatus"))).ToolTip = this.GetLabel("SOM_Saved", false);
                }
                else
                {
                    ((Image)(e.Row.Cells[6].FindControl("imgSaveStatus"))).ImageUrl = Request.ApplicationPath + "/Images/SOM/UnsaveStatus.gif";
                    ((Image)(e.Row.Cells[6].FindControl("imgSaveStatus"))).ToolTip = this.GetLabel("SOM_UnSave", false);
                }

                string strURL = string.Empty;

                /****************************add by dylan 20150710 for u96 start***********************************/
                if (DAL.Security.User.CanFunctionItemAccess("M140102_F9", this.ODMUser.UserProfileID, this.MenuID))
                {
                    ((ImageButton)(e.Row.Cells[10].FindControl("imgDelete"))).Visible = true;
                    ((ImageButton)(e.Row.Cells[10].FindControl("imgDelete"))).Enabled = true;
                    ((ImageButton)(e.Row.Cells[10].FindControl("imgDelete"))).Attributes.Add("style", "cursor:hand;");
                    ((ImageButton)(e.Row.Cells[10].FindControl("imgDelete"))).Attributes.Add("onclick", "return confirm('" + GetMessage("COM_ConfirmSubmit") + "');");
                }
                else
                {
                    ((ImageButton)(e.Row.Cells[10].FindControl("imgDelete"))).Visible = false;
                    ((ImageButton)(e.Row.Cells[10].FindControl("imgDelete"))).Enabled = false;
                    ((ImageButton)(e.Row.Cells[10].FindControl("imgDelete"))).ImageUrl = Request.ApplicationPath + "/Images/SOM/ARFire_deleted.gif";
                    //((ImageButton)(e.Row.Cells[8].FindControl("imgDelete"))).ToolTip = this.GetLabel("SOM_Deleted", false);
                }
                /****************************add by dylan 20150710 for u96 end***********************************/

                //read only check
                if (DAL.Security.User.CanFunctionItemAccess("M140102_F1", this.ODMUser.UserProfileID, this.MenuID) != true && hdnStatus.Value != "2")
                {
                    //record is Obsolete or not,the img will change
                    if (grdFireSystem.DataKeys[e.Row.RowIndex]["FlagObsolete"].ToString().ToLower() == "false")
                    {
                        //strURL = "../Popup/PopupARFirePortection.aspx?Action=" + strAction + "&ParentStationEventID=" + strParentStationEventID + "&ParentEventNo=" + strParentEvenNo + "&tempID=" + strtempID + "&StationEventID=" + strStationEventID + "&StatffID=" + txtStaffID + "&lblIsolationDateTime=" + lblIsolationDateTime + "&imgRequesSrc=" + imgRequesSrc + "&txtRequestByName=" + txtRequestByName + "&txtRequestByDept=" + txtRequestByDept + "&txtRequestByOU=" + txtRequestByOU + "&txtRequestByContactNumber=" + txtRequestByContactNumber + "&txtIsolationDuration=" + txtIsolationDuration + "&lblEstimatedIsolationDate=" + lblEstimatedIsolationDate + "&chkHandoverCheck=" + chkHandoverCheck + "&txtHandoverNote=" + txtHandoverNote + "&hdnInitDateTime=" + hdnInitDateTime + "&hdnRequestStaffOrExtPartyID=" + hdnRequestStaffOrExtPartyID + "&hdnStaffType=" + hdnStaffType;
                        //strURL = "../Popup/PopupARFirePortection.aspx?Action=" + strAction + "&ParentStationEventID=" + strParentStationEventID + "&ParentEventNo=" + strParentEvenNo + "&tempID=" + strtempID + "&StationEventID=" + strStationEventID + "&StatffID=" + txtStaffID + "&lblIsolationDateTime=" + lblIsolationDateTime + "&imgRequesSrc=" + imgRequesSrc + "&txtRequestByName=" + txtRequestByName + "&txtRequestByDept=" + txtRequestByDept + "&txtRequestByOU=" + txtRequestByOU + "&txtRequestByContactNumber=" + txtRequestByContactNumber + "&txtIsolationDuration=" + txtIsolationDuration + "&lblEstimatedIsolationDate=" + lblEstimatedIsolationDate + "&chkHandoverCheck=" + chkHandoverCheck + "&txtHandoverNote=" +this.txtHandoverCheckDetail.Text + "&hdnInitDateTime=" + hdnInitDateTime + "&hdnRequestStaffOrExtPartyID=" + hdnRequestStaffOrExtPartyID + "&hdnStaffType=" + hdnStaffType;
                        // edit by dylan 20150928 for u196

                        strURL = "../Popup/PopupARFirePortection.aspx?Action=" + this.Server.UrlEncode(strAction) + "&ParentStationEventID=" + this.Server.UrlEncode(strParentStationEventID) + "&ParentEventNo=" + this.Server.UrlEncode(strParentEvenNo) + "&tempID=" + this.Server.UrlEncode(strtempID) + "&StationEventID=" + this.Server.UrlEncode(strStationEventID) + "&StatffID=" + this.Server.UrlEncode(txtStaffID) + "&lblIsolationDateTime=" + this.Server.UrlEncode(lblIsolationDateTime) + "&imgRequesSrc=" + this.Server.UrlEncode(imgRequesSrc) + "&txtRequestByName=" + this.Server.UrlEncode(txtRequestByName) + "&txtRequestByDept=" + this.Server.UrlEncode(txtRequestByDept) + "&txtRequestByOU=" + this.Server.UrlEncode(txtRequestByOU) + "&txtRequestByContactNumber=" + this.Server.UrlEncode(txtRequestByContactNumber) + "&txtIsolationDuration=" + this.Server.UrlEncode(txtIsolationDuration) + "&lblEstimatedIsolationDate=" + this.Server.UrlEncode(lblEstimatedIsolationDate) + "&hdnInitDateTime=" + this.Server.UrlEncode(hdnInitDateTime) + "&hdnRequestStaffOrExtPartyID=" + this.Server.UrlEncode(hdnRequestStaffOrExtPartyID) + "&hdnStaffType=" + this.Server.UrlEncode(hdnStaffType.ToString());
                        ((Image)(e.Row.Cells[9].FindControl("imgEdit"))).Attributes.Add("onclick", "javascript:return EditFireSystem('" + strURL + "');");
                    }
                    else
                    {
                        //strURL = "../Popup/PopupARFirePortection.aspx?Action=" + strAction + "&ReadOnly=1" + "&ParentStationEventID=" + strParentStationEventID + "&ParentEventNo=" + strParentEvenNo + "&tempID=" + strtempID + "&StationEventID=" + strStationEventID + "&StatffID=" + txtStaffID + "&lblIsolationDateTime=" + lblIsolationDateTime + "&imgRequesSrc=" + imgRequesSrc + "&txtRequestByName=" + txtRequestByName + "&txtRequestByDept=" + txtRequestByDept + "&txtRequestByOU=" + txtRequestByOU + "&txtRequestByContactNumber=" + txtRequestByContactNumber + "&txtIsolationDuration=" + txtIsolationDuration + "&lblEstimatedIsolationDate=" + lblEstimatedIsolationDate + "&chkHandoverCheck=" + chkHandoverCheck + "&txtHandoverNote=" + txtHandoverNote + "&hdnInitDateTime=" + hdnInitDateTime + "&hdnRequestStaffOrExtPartyID=" + hdnRequestStaffOrExtPartyID + "&hdnStaffType=" + hdnStaffType;
                        strURL = "../Popup/PopupARFirePortection.aspx?Action=" + this.Server.UrlEncode(strAction) + "&ReadOnly=1" + "&ParentStationEventID=" + this.Server.UrlEncode(strParentStationEventID) + "&ParentEventNo=" + this.Server.UrlEncode(strParentEvenNo) + "&tempID=" + this.Server.UrlEncode(strtempID) + "&StationEventID=" + this.Server.UrlEncode(strStationEventID) + "&StatffID=" + this.Server.UrlEncode(txtStaffID) + "&lblIsolationDateTime=" + this.Server.UrlEncode(lblIsolationDateTime) + "&imgRequesSrc=" + this.Server.UrlEncode(imgRequesSrc) + "&txtRequestByName=" + this.Server.UrlEncode(txtRequestByName) + "&txtRequestByDept=" + this.Server.UrlEncode(txtRequestByDept) + "&txtRequestByOU=" + this.Server.UrlEncode(txtRequestByOU) + "&txtRequestByContactNumber=" + this.Server.UrlEncode(txtRequestByContactNumber) + "&txtIsolationDuration=" + this.Server.UrlEncode(txtIsolationDuration) + "&lblEstimatedIsolationDate=" + this.Server.UrlEncode(lblEstimatedIsolationDate) + "&chkHandoverCheck=" + this.Server.UrlEncode(chkHandoverCheck.ToString()) + "&txtHandoverNote=" + "" + "&hdnInitDateTime=" + this.Server.UrlEncode(hdnInitDateTime) + "&hdnRequestStaffOrExtPartyID=" + this.Server.UrlEncode(hdnRequestStaffOrExtPartyID) + "&hdnStaffType=" + this.Server.UrlEncode(hdnStaffType.ToString());
                        ((Image)(e.Row.Cells[9].FindControl("imgEdit"))).Attributes.Add("onclick", "javascript:return EditFireSystem('" + strURL + "');");

                    }
                }
                else
                {
                    //strURL = "../Popup/PopupARFirePortection.aspx?Action=" + strAction + "&ReadOnly=1" + "&ParentStationEventID=" + strParentStationEventID + "&ParentEventNo=" + strParentEvenNo + "&tempID=" + strtempID + "&StationEventID=" + strStationEventID + "&StatffID=" + txtStaffID + "&lblIsolationDateTime=" + lblIsolationDateTime + "&imgRequesSrc=" + imgRequesSrc + "&txtRequestByName=" + txtRequestByName + "&txtRequestByDept=" + txtRequestByDept + "&txtRequestByOU=" + txtRequestByOU + "&txtRequestByContactNumber=" + txtRequestByContactNumber + "&txtIsolationDuration=" + txtIsolationDuration + "&lblEstimatedIsolationDate=" + lblEstimatedIsolationDate + "&chkHandoverCheck=" + chkHandoverCheck + "&txtHandoverNote=" + txtHandoverNote + "&hdnInitDateTime=" + hdnInitDateTime + "&hdnRequestStaffOrExtPartyID=" + hdnRequestStaffOrExtPartyID + "&hdnStaffType=" + hdnStaffType;
                    strURL = "../Popup/PopupARFirePortection.aspx?Action=" + this.Server.UrlEncode(strAction) + "&ReadOnly=1" + "&ParentStationEventID=" + this.Server.UrlEncode(strParentStationEventID) + "&ParentEventNo=" + this.Server.UrlEncode(strParentEvenNo) + "&tempID=" + this.Server.UrlEncode(strtempID) + "&StationEventID=" + this.Server.UrlEncode(strStationEventID) + "&StatffID=" + this.Server.UrlEncode(txtStaffID) + "&lblIsolationDateTime=" + this.Server.UrlEncode(lblIsolationDateTime) + "&imgRequesSrc=" + this.Server.UrlEncode(imgRequesSrc) + "&txtRequestByName=" + this.Server.UrlEncode(txtRequestByName) + "&txtRequestByDept=" + this.Server.UrlEncode(txtRequestByDept) + "&txtRequestByOU=" + this.Server.UrlEncode(txtRequestByOU) + "&txtRequestByContactNumber=" + this.Server.UrlEncode(txtRequestByContactNumber) + "&txtIsolationDuration=" + this.Server.UrlEncode(txtIsolationDuration) + "&lblEstimatedIsolationDate=" + this.Server.UrlEncode(lblEstimatedIsolationDate) + "&chkHandoverCheck=" + this.Server.UrlEncode(chkHandoverCheck.ToString()) + "&txtHandoverNote=" + "" + "&hdnInitDateTime=" + this.Server.UrlEncode(hdnInitDateTime) + "&hdnRequestStaffOrExtPartyID=" + this.Server.UrlEncode(hdnRequestStaffOrExtPartyID) + "&hdnStaffType=" + this.Server.UrlEncode(hdnStaffType.ToString());
                    ((Image)(e.Row.Cells[9].FindControl("imgEdit"))).Attributes.Add("onclick", "javascript:return EditFireSystem('" + strURL + "');");

                    //((ImageButton)(e.Row.Cells[8].FindControl("imgDelete"))).Visible = false;
                    //((ImageButton)(e.Row.Cells[8].FindControl("imgDelete"))).Enabled = false;
                    //record is Obsolete ,the img will change
                    //if (grdFireSystem.DataKeys[e.Row.RowIndex]["FlagObsolete"].ToString().ToLower() == "false")
                    //{
                    //    ((ImageButton)(e.Row.Cells[8].FindControl("imgDelete"))).ImageUrl = Request.ApplicationPath + "/Images/SOM/ARFire_deleted.gif";
                    //    ((ImageButton)(e.Row.Cells[8].FindControl("imgDelete"))).ToolTip = this.GetLabel("SOM_Deleted", false);
                    //}
                }
                //add by benson 2015-08-26 :u171 begin
                if (((Label)e.Row.Cells[7].Controls[1]).Text == "")
                {
                    ((Image)e.Row.Cells[7].Controls[3]).Visible = false;
                }
                else if (((Label)e.Row.Cells[7].Controls[1]).Text == "1")
                {
                    ((Image)e.Row.Cells[7].Controls[3]).Visible = true;
                    ((Image)e.Row.Cells[7].Controls[3]).ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_OS.gif";
                    //                    ((ImageButton)e.Row.Cells[6].Controls[2]).ToolTip = this.GetLabel("SOM_OS", false);
                    ((Image)e.Row.Cells[7].Controls[3]).ToolTip = ((HiddenField)e.Row.Cells[7].FindControl("hfEventStatusDesc")).Value;
                }
                else if (((Label)e.Row.Cells[7].Controls[1]).Text == "2")
                {
                    ((Image)e.Row.Cells[7].Controls[3]).Visible = true;
                    ((Image)e.Row.Cells[7].Controls[3]).ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_COM.gif";
                    //((ImageButton)e.Row.Cells[6].Controls[2]).ToolTip = this.GetLabel("SOM_Completed", false);
                    ((Image)e.Row.Cells[7].Controls[3]).ToolTip = ((HiddenField)e.Row.Cells[7].FindControl("hfEventStatusDesc")).Value;
                }
                else
                {
                    ((Image)e.Row.Cells[7].Controls[3]).Visible = true;
                    ((Image)e.Row.Cells[7].Controls[3]).ImageUrl = Request.ApplicationPath.ToString() + "/Images/SOM/EventStatus_Void.gif";
                    //((ImageButton)e.Row.Cells[6].Controls[2]).ToolTip = this.GetLabel("SOM_Void", false);
                    ((Image)e.Row.Cells[7].Controls[3]).ToolTip = ((HiddenField)e.Row.Cells[7].FindControl("hfEventStatusDesc")).Value;
                }
                //update by benson 2015.08.27 u183.3 begin
                if (((Label)e.Row.Cells[8].Controls[1]).Text == "")
                {
                    ((Image)e.Row.Cells[8].Controls[3]).Visible = false;
                }
                else if (((Label)e.Row.Cells[7].Controls[1]).Text == "2")
                {
                    ((Image)e.Row.Cells[8].Controls[3]).Visible = true;
                    ((Image)e.Row.Cells[8].Controls[3]).ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                    ((Image)e.Row.Cells[8].Controls[3]).ToolTip = this.GetLabel("SOM_HighLightNormal", false);
                }
                //update by benson 2015.08.27 u183.3 end
                else if (((Label)e.Row.Cells[8].Controls[1]).Text == "1")
                {
                    ((Image)e.Row.Cells[8].Controls[3]).Visible = true;
                    ((Image)e.Row.Cells[8].Controls[3]).ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Yellow.gif";
                    ((Image)e.Row.Cells[8].Controls[3]).ToolTip = this.GetLabel("SOM_HighLightYellow", false);
                }
                else if (((Label)e.Row.Cells[8].Controls[1]).Text == "2")
                {
                    ((Image)e.Row.Cells[8].Controls[3]).Visible = true;
                    ((Image)e.Row.Cells[8].Controls[3]).ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Red.gif";
                    ((Image)e.Row.Cells[8].Controls[3]).ToolTip = this.GetLabel("SOM_HighLightRed", false);
                }
                else
                {
                    ((Image)e.Row.Cells[8].Controls[3]).Visible = true;
                    ((Image)e.Row.Cells[8].Controls[3]).ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                    ((Image)e.Row.Cells[8].Controls[3]).ToolTip = this.GetLabel("SOM_HighLightNormal", false);
                }
                //add by benson 2015-08-26 :u171 end
            }
        }

        protected void grdAssetLoan_NeedDataBind()
        {
            SettingAssetLoanGridByData();
        }

        protected void grdAssetLoan_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }


        //1467
        protected void imgCompletionTasksDeparture_Click(object sender, ImageClickEventArgs e)
        {
            DepartureCheck(1);
        }

        /// <summary>
        /// CheckUnRestore
        /// add by gordon 20150811 U147
        /// </summary>
        /// <returns></returns>
        private bool CheckUnRestore()
        {
            string result = "2";
            string controlKey = "-1";

            string tempId = Request.Form["TEMPID"];
            string mode = Request.QueryString["MODE"];
            if (!string.IsNullOrEmpty(tempId) && mode == "chkUnRestore")
            {
                try
                {
                    int unRestoreStationEventId = -1;
                    int tid = -1;
                    int.TryParse(tempId, out tid);
                    string xml = DAL.SOM.TempData.GetTempDataByID(tid);
                    if (!string.IsNullOrEmpty(xml))
                    {
                        XElement doc = XElement.Parse(xml);
                        List<XElement> stationEvents = doc.Descendants("SOM_StationEvent").ToList();
                        foreach (XElement element in stationEvents)
                        {
                            string eventStatusID = element.Element("EventStatusID").Value;
                            if (eventStatusID != "2")
                            {
                                result = eventStatusID;
                                int tempSid = -1;
                                int.TryParse(element.Element("StationEventID").Value, out tempSid);
                                unRestoreStationEventId = tempSid;
                                break;
                            }
                        }
                    }

                    controlKey = unRestoreStationEventId.ToString();
                }
                catch
                {

                }

                Response.Write(result + "-" + controlKey);
                Response.End();
                return true;
            }
            return false;
        }

        //1467
        /// <summary>
        /// update by benson 2015.07.29 U102 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeparture_Click(object sender, EventArgs e)
        {
            DepartureCheck(2);
        }

        protected void hdnRefash_ServerChange(object sender, EventArgs e)
        {
            this.SettingFireGridByDataBind();
            this.hdnRefash.Value = "";
        }

        void grdFireSystem_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            int nFireKey = Convert.ToInt32(hdnFireSystemKey.Value);
            int nFireStationEventID = Convert.ToInt32(this.grdFireSystem.DataKeys[e.RowIndex]["StationEventID"].ToString());
            BLL.SOM.Event.FireProtection.UpdateTempData_DeleteEvent(nFireKey, nFireStationEventID);
            SettingFireGridByDataBind();
        }

        protected void grdFireSystem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
        }

        protected void hdnAssetLoanItemTmpIDChangeFlag_ServerChange(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            //update by benson 2015.07.27  U102 begin
            this.ucSignatureNew1.IsNeedSignAgain = true;
            //ucSignatureArrivalBottom.IsNeedSignAgain = true;
            if (ucSignatureNew1.GetSignatureFullFileName(2).ToString() != string.Empty)
            {
                this.ucSignatureNew1.IsNeedSignAgain = true;
                //ucSignatureDepartureBottom.IsNeedSignAgain = true;
            }
            //update by benson 2015.07.27  U102 end
            SettingAssetLoanGridByData();
        }

        protected void btnCloseRecord_ServerClick(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            DepartureCheck(1);
        }

        protected void chkObsolete_CheckedChanged(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            if (chkObsolete.Checked == true)
            {
                if (hdnFireSystemKey.Value == string.Empty)
                {
                    //1:AR;2:asset loan; 3:fire
                    string xml = BLL.SOM.Event.FireProtection.CreateDataSetXml(this.LangCode, this.StationEventID);
                    int tempID = DAL.SOM.TempData.AddTempData(this.ODMUser.ID, this.ODMUser.Domain, xml);
                    //tempID = 5201;
                    hdnFireSystemKey.Value = tempID.ToString();
                    DataTable dtFireGridList = BLL.SOM.Event.StationEventAdmReg.GetFireGridListByKey(tempID, this.LangCode);
                    grdFireSystem.DataSource = dtFireGridList.DefaultView;
                    grdFireSystem.DataBind();
                }
                else
                {
                    int nFireSystemKey = Convert.ToInt32(hdnFireSystemKey.Value);
                    DataTable dtFireGridList = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.GetFireGridListByKey(nFireSystemKey, this.LangCode);
                    grdFireSystem.DataSource = dtFireGridList.DefaultView;
                    grdFireSystem.DataBind();
                }
            }
            else
            {
                SettingFireGridByDataBind();
            }
        }

        protected void btnAssetLoanItemTmpIDChangeFlag_ServerClick(object sender, EventArgs e)
        {
            this.AjaxUpdateIsServerChanged();
            //update by benson 2015.07.27  U102 begin
            //this.ucSignatureNew1.IsNeedSignAgain = true;
            //ucSignatureArrivalBottom.IsNeedSignAgain = true;
            //if (ucSignatureNew1.GetSignatureFullFileName(2).ToString() != string.Empty)
            //{
            //this.ucSignatureNew1.IsNeedSignAgain = true;
            //ucSignatureDepartureBottom.IsNeedSignAgain = true;
            //}
            //update by benson 2015.07.27  U102 end
            SettingAssetLoanGridByData();
        }

        protected void btnRefurbish_Click(object sender, EventArgs e)
        {
            chkObsolete_CheckedChanged(null, EventArgs.Empty);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            //rblEngineControlSystemFirst.Items[0].Attributes.Add("myDefaultValue", rblEngineControlSystemFirst.Items[0].Selected.ToString().ToLower());
            //rblEngineControlSystemFirst.Items[1].Attributes.Add("myDefaultValue", rblEngineControlSystemFirst.Items[1].Selected.ToString().ToLower());
            this.chkHandoverCheck.Attributes.Add("onclick", "chkHandoerClick(this,'" + GetMessage("SOM_CancelHandoverNoteConfirm", this.LangCode) + "');");
            bool bIsTNProtected, bIsUserValidateNeeded;
            bIsTNProtected = IsTNProtected();
            bIsUserValidateNeeded = IsUserValidate();

            this.btnSave.OnClientClick = string.Format("return Save('{0}','{1}','{2}');", bIsUserValidateNeeded.ToString().ToLower(), this.ODMUser.UserID, this.ODMUser.Domain);
            //string strSaveScript = "<script language='javascript'> return Save('" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus21", strSaveScript, false);

            //btnSaveBottom.OnClientClick = string.Format("return Save('{0}');", bIsUserValidateNeeded.ToString().ToLower());
            //btnSaveBottom.Attributes.Add("onclick", "Save2('" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            //AjaxControlToolkit.ToolkitScriptManager.RegisterExpandoAttribute(this, "btnSaveBottom", "onclick", "return Save('" + bIsUserValidateNeeded.ToString().ToLower() + "');", false);
            //string strSaveBottomOnClientClick = "<script language='javascript'>Save('" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus22", strSaveBottomOnClientClick, false);

            //btnSaveTop.OnClientClick = string.Format("return Save('{0}');", bIsUserValidateNeeded.ToString().ToLower());
            //string strbtnSaveTopOnClientClick = "<script language='javascript'>Save('" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus23", strbtnSaveTopOnClientClick, false);
            //AjaxControlToolkit.ToolkitScriptManager.RegisterExpandoAttribute(this, "btnSaveTop", "onclick", "return Save('" + bIsUserValidateNeeded.ToString().ToLower() + "');", false);
            btnSaveTop.Attributes.Add("onclick", "Save2('" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");

            //this.imgCompletionTasksDeparture.OnClientClick = string.Format("return DepartStation(document.getElementById('hdnStationEventID').value,1,'M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //this.imgDeparture.OnClientClick = string.Format("return DepartStation(document.getElementById('hdnStationEventID').value,2,'M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //this.imgCompletionTasksDeparture.OnClientClick = string.Format("return DepartStation('M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //string strimgCompletionTasksDeparture = "<script language='javascript'>DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus24", strimgCompletionTasksDeparture, false);

            //update by benson 2015.07.27 u102 begin
            //imgCompletionTasksDeparture.Attributes.Add("onclick", "DepartStation(document.getElementById('hdnStationEventID').value,1,'M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            //update by benson 2015.07.27 u102 end

            //imgCompletionTasksDepartureBottom.OnClientClick = string.Format("return DepartStation('M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //string strimgimgCompletionTasksDepartureBottom = "<script language='javascript'>return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus25", strimgimgCompletionTasksDepartureBottom, false);

            // Commented by Kingkong Chan 20150803
            //imgCompletionTasksDeparture.Attributes.Add("onclick", "DepartStation(document.getElementById('hdnStationEventID').value,1,'M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            // Commented by Kingkong Chan 20150803
            //imgCompletionTasksDeparture.Attributes.Add("onclick", "return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");

            //imgCompletionTasksDepartureBottom.OnClientClick = string.Format("return DepartStation('M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //string strimgimgCompletionTasksDepartureBottom = "<script language='javascript'>return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus25", strimgimgCompletionTasksDepartureBottom, false);
            // Commented by Kingkong Chan 20150803
            //imgCompletionTasksDepartureBottom.Attributes.Add("onclick", "DepartStation(document.getElementById('hdnStationEventID').value,1,'M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            // Commented by Kingkong Chan 20150803
            //imgCompletionTasksDepartureBottom.Attributes.Add("onclick", "return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");

            //this.imgDeparture.OnClientClick = string.Format("return DepartStation('M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //string strimgDeparture = "<script language='javascript'>return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus26", strimgDeparture, false);
            // Updated by Kingkong Chan 20150803
            //imgDeparture.Attributes.Add("onclick", "return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            // Updated by Kingkong Chan 20150803

            //imgDepartureBottom.OnClientClick = string.Format("return DepartStation('M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //string strimgDepartureBottom = "<script language='javascript'>return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus27", strimgDepartureBottom, false);
            // Updated by Kingkong Chan 20150803
            //imgDepartureBottom.Attributes.Add("onclick", "return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            // Updated by Kingkong Chan 20150803

            //update by benson 2015.07.27 u102 begin
            //imgCompletionTasksDepartureBottom.Attributes.Add("onclick", "DepartStation(document.getElementById('hdnStationEventID').value,1,'M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            //update by benson 2015.07.27 u102 end

            //this.imgDeparture.OnClientClick = string.Format("return DepartStation('M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //string strimgDeparture = "<script language='javascript'>return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus26", strimgDeparture, false);
            //update by benson 2015.07.27 u102 begin
            //imgDeparture.Attributes.Add("onclick", "DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            //update by gordon 20150811 U147
            //btnDeparture.Attributes.Add("onclick", "DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            btnDeparture.Attributes.Add("onclick", "return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            //-----------------------------
            //update by benson 2015.07.27 u102 begin
            //imgDepartureBottom.OnClientClick = string.Format("return DepartStation('M140102','{0}','{1}');", bIsTNProtected.ToString().ToLower(), bIsUserValidateNeeded.ToString().ToLower());
            //string strimgDepartureBottom = "<script language='javascript'>return DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "');</script>";
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(BasePage), "onfocus27", strimgDepartureBottom, false);

            //update by benson 2015.07.27 u102 begin
            //imgDepartureBottom.Attributes.Add("onclick", "DepartStation('M140102','" + bIsTNProtected.ToString().ToLower() + "','" + bIsUserValidateNeeded.ToString().ToLower() + "','" + this.ODMUser.UserID + "','" + this.ODMUser.Domain + "');");
            //update by benson 2015.07.27 u102 end

            //this.btnMoreQualification.OnClientClick = string.Format("return PersonSelectdQual('{0}','{1}','{2}')", HttpUtility.UrlEncode(this.txtStaffID.Text), hdnStaffType.Value, hdnPersonHoldQualKye.Value);
        }

        //add by jack 20150630 for U50
        protected void ddlDepartmentCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectValue = ddlDepartmentCompany.SelectedValue;
            this.txtDepartmentCompany.Text = selectValue;
        }

        protected void ddlQualification_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ddlQualification.SelectedItem.Value) && !ddlQualification.SelectedItem.Value.Equals(this.GetMessage("SOM_QualificationNotFound")))
            {

            }
        }

        #endregion

        //add by tim 20160701
        protected void hidBtton_Click(object sender, EventArgs e)
        {
            string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
            Session[signatureName] = this.ucSignatureNew1.SignatureTemp;
        }
        //end add

        #region Code by Huangyao, for Test ,do not delete

        protected void btnSaveInAR_Click(object sender, EventArgs e)
        {
            //int assetLoanDataTmpID = -1;
            //int.TryParse(this.hdnAssetLoanMainDataTmpID.Value.Trim(), out assetLoanDataTmpID);
            //int assetLoanItemDataTmpID = -1;
            //int.TryParse(this.hdnAssetLoanItemDataTmpID.Value.Trim(), out assetLoanItemDataTmpID);

            //int userID = this.ODMUser.ID;

            ////---------those code should Comment when in HZX AR page, here only for test---------------------
            //try
            //{
            //    this.StationEventID = MTRC.ODMS.BLL.SOM.Event.StationEventAssetLoan.ALDataInARPageSaveToDB(this.StationEventID, assetLoanDataTmpID, assetLoanItemDataTmpID, userID, this.LangCode,null);
            //    this.Alert(this.GetMessage("SaveSuccessfully"));
            //}
            //catch (Exception ex)
            //{
            //    //Alert(ex.Message);
            //    //SaveUnsuccessfully
            //    this.Alert(this.GetMessage("SaveUnsuccessfully") + " : " + ex.Message);
            //}
            ////-------end--those code should Comment when in HZX AR page, here only for test---------------------
        }

        #endregion

        //private void ExportAfterSave()
        //{
        //    int nSumEventNoOfWorkers = 0;
        //    int nCountCompany = 0;
        //    DataSet dsExport = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.GetAREntryExport(this.LangCode, ref nSumEventNoOfWorkers, ref nCountCompany);
        //    DataTable dtExport = new DataTable();
        //    dtExport = dsExport.Tables[0];
        //    dtExport.Columns["CreateTime"].ColumnName = this.GetLabel("SOM_StationEventCreateTime");
        //    dtExport.Columns["EventTime"].ColumnName = this.GetLabel("SOM_ArrivalTime");
        //    dtExport.Columns["StaffName"].ColumnName = this.GetLabel("COM_StaffName");
        //    dtExport.Columns["DepartmentCompany"].ColumnName = this.GetLabel("SOM_DepartmentCompany");
        //    dtExport.Columns["Tel"].ColumnName = this.GetLabel("COM_ContactNo");
        //    dtExport.Columns["EventNoOfWorkers"].ColumnName = this.GetLabel("SOM_NumberOfWorkers");
        //    dtExport.Columns["JobNature"].ColumnName = this.GetLabel("SOM_JobNature");
        //    dtExport.Columns["JobLocation"].ColumnName = this.GetLabel("SOM_JobLocation");

        //    DataView dvLocation = new DataView(ODMS.DAL.SOM.CodeSetup.CDLocation.GetLocation(this.LangCode));
        //    dvLocation.RowFilter = "StationID=" + this.ODMUser.LocationID;
        //    string fileName = dvLocation[0]["LocationCode"].ToString() + ".html";
        //    Context.Response.Clear();
        //    Context.Response.Charset = "UTF-16";
        //    Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(1200);
        //    Context.Response.AddHeader("Content-disposition", "attachment;filename=" + fileName);
        //    Context.Response.ContentType = "text/html";

        //    genExcel_showHHMM(dsExport, Context, false, null);
        //}

        //private void genExcel_showHHMM(DataSet ds, System.Web.HttpContext context, bool addSerialNumber, string serialNumberColumnName)
        //{
        //    string xslFile = System.IO.Path.Combine(context.Request.PhysicalApplicationPath, "XSL/HtmlExport.xslt");
        //    XmlDocument XmlDoc = new XmlDocument();
        //    XmlNode tableNode, columnsNode, rowsNode, rowNode, colNode;
        //    XmlNode parentNode;
        //    string s = "";

        //    XmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-16\" ?><DataSet />");

        //    parentNode = XmlDoc.DocumentElement;
        //    APJ.Util.Utility.AddAttribute(parentNode, "count", ds.Tables.Count.ToString());

        //    foreach (DataTable dt in ds.Tables)
        //    {
        //        int rowCount = 0;
        //        tableNode = APJ.Util.Utility.AddNode(parentNode, "Table", "");
        //        APJ.Util.Utility.AddAttribute(tableNode, "name", dt.TableName);
        //        columnsNode = APJ.Util.Utility.AddNode(tableNode, "columns", "");
        //        APJ.Util.Utility.AddAttribute(columnsNode, "count", dt.Columns.Count.ToString());

        //        if (addSerialNumber)
        //            APJ.Util.Utility.AddNode(columnsNode, "column", "", serialNumberColumnName);

        //        foreach (DataColumn dataColumn in dt.Columns)
        //        {
        //            APJ.Util.Utility.AddNode(columnsNode, "column", "", dataColumn.ColumnName);
        //        }

        //        rowsNode = APJ.Util.Utility.AddNode(tableNode, "rows", "");
        //        foreach (DataRow dataRow in dt.Rows)
        //        {
        //            rowCount++;
        //            rowNode = APJ.Util.Utility.AddNode(rowsNode, "row", "");
        //            if (addSerialNumber)
        //            {
        //                colNode = APJ.Util.Utility.AddNode(rowNode, "col", "", rowCount.ToString());
        //                APJ.Util.Utility.AddAttribute(colNode, "type", "Number");
        //            }
        //            foreach (DataColumn dataColumn in dt.Columns)
        //            {
        //                s = dataRow[dataColumn].ToString();
        //                s = context.Server.HtmlEncode(s);
        //                s = s.Replace(System.Char.ToString((char)10), "&#10;");

        //                colNode = APJ.Util.Utility.AddNode(rowNode, "col", "", s);
        //                string type = "";
        //                switch (System.Type.GetTypeCode(dataColumn.DataType))
        //                {
        //                    case System.TypeCode.Int16:
        //                    case System.TypeCode.Int32:
        //                    case System.TypeCode.Int64:
        //                    case System.TypeCode.Single:
        //                    case System.TypeCode.Double:
        //                    case System.TypeCode.Decimal:
        //                    case System.TypeCode.UInt16:
        //                    case System.TypeCode.UInt32:
        //                    case System.TypeCode.UInt64:
        //                        type = "Number";
        //                        break;
        //                    case System.TypeCode.DateTime:
        //                        type = "DateTime";
        //                        if ((dataRow[dataColumn] == null) || (dataRow[dataColumn] is DBNull))
        //                            colNode.InnerText = "";
        //                        else
        //                            colNode.InnerText = ((DateTime)dataRow[dataColumn]).ToString("yyyy-MM-ddTHH:mm", System.Globalization.DateTimeFormatInfo.InvariantInfo);

        //                        break;
        //                    default:
        //                        type = "String";
        //                        break;
        //                }
        //                APJ.Util.Utility.AddAttribute(colNode, "type", type);
        //            }
        //        }
        //    }

        //    //XslTransform xsl = new XslTransform();
        //    //xsl.Load(xslFile);
        //    //xsl.Transform(XmlDoc, null, context.Response.OutputStream, null);

        //    XslCompiledTransform xslt = new XslCompiledTransform();
        //    xslt.Load(xslFile);
        //    XmlWriter writer = XmlWriter.Create(context.Response.OutputStream, xslt.OutputSettings);
        //    xslt.Transform(XmlDoc, writer);
        //    writer.Close();
        //    context.Response.End();
        //}
    }

    //this.ClientScript.RegisterStartupScript(typeof(BasePage), "OpenDepatureForm", string.Format("<script language='javascript'>DepartStation('{0}','{1}','{2}')</script>", this.StationEventID, 1, this.MenuID));
}
